class Solution {
public:
    int binaryGap(int N) {
        int position = 0;
        vector<int> V;
        while (N)
        {
            if (N & 1)//N&1==1,表示最后一位是1
            {
                V.push_back(position);//把二进制为1的下标都记录下来
            }

            position++;
            N >>= 1;//右移一位
        }
        
        if (V.size() <= 1)
        {
            return 0;
        }
        //1 2 4
        int maxdistance = 0;
        int lastPosition = -1;
        for (int i = 0; i < V.size(); i++)
        {
            cout << V[i] << " ";
            if (i == 0)
            {
                lastPosition = V[i];
            }
            else
            {
                int distance = V[i] - lastPosition;
                if (maxdistance < distance)
                {
                    maxdistance = distance;
                }
                lastPosition = V[i];
            }
        }
        return maxdistance;
    }
};

 

posted on 2018-09-28 19:45  Sempron2800+  阅读(84)  评论(0编辑  收藏  举报