[leetcode]868. Binary Gap

[leetcode]868. Binary Gap


Analysis

old friends~—— [嘻嘻~]

Given a positive integer N, find and return the longest distance between two consecutive 1’s in the binary representation of N.
If there aren’t two consecutive 1’s, return 0.
转换成二进制,然后判断连续两个1之间的距离,返回最大距离就行了~

Implement

class Solution {
public:
    int binaryGap(int N) {
        vector<int> bi;
        while(N){
            bi.push_back(N%2);
            N /= 2;
        }
        int pre = -1;
        int res = 0;
        for(int i=0; i<bi.size(); i++){
            if(bi[i] == 1){
                if(pre == -1)
                    pre = i;
                else{
                    res = max(res, i-pre);
                    pre = i;
                }
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81254160
GAP
GAP