[LeetCode] 868. Binary Gap 二进制间隙



Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.html

If there aren't two consecutive 1's, return 0.git

Example 1:github

Input: 22
Output: 2
Explanation:
22 in binary is 0b10110.
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
The first consecutive pair of 1's have distance 2.
The second consecutive pair of 1's have distance 1.
The answer is the largest of these two distances, which is 2.

Example 2:数组

Input: 5
Output: 2
Explanation:
5 in binary is 0b101.

Example 3:code

Input: 6
Output: 1
Explanation:
6 in binary is 0b110.

Example 4:htm

Input: 8
Output: 0
Explanation:
8 in binary is 0b1000.
There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.

Note:blog

  • 1 <= N <= 10^9



这道题给了咱们一个正整数,问其二进制表示数中两个 '1' 之间的最大距离是多少。好比整数 22 的二进制为 10110,那么能够看出前两个 '1' 之间的距离最大,因此返回2便可。其实这道题的考察点就是如何按位取数,对一个二进制数直接与 '1',就能够提取出最低位,而后和0比较大小,就知道最低位是0仍是1了。固然为了每一位的是0仍是1,通常有两种处理方法,一种是直接将原数字右移一位,则以前的最低位被移除了,再和 '1' 相与便可,直到原数字变为0中止。另外一种方法是直接右移固定的位数再与 '1',由于整型数只有 32 位,因此能够直接取出任意位上的数字。那么既然要求两个 '1' 之间的最大距离,那么只要关心 '1' 的位置便可,一种比较直接的思路就是先遍历一遍各位上的数字,将全部 '1' 的坐标位置都保存到一个数组 pos 之中,而后再遍历这个 pos 数组,计算相邻两个数字的差,即两个 '1' 之间的距离,更新结果 res 便可获得最大距离,参见代码以下:three



解法一:leetcode

class Solution {
public:
    int binaryGap(int N) {
        vector<int> pos;
        for (int i = 0; i < 32; ++i) {
            if (((N >> i) & 1) != 0) pos.push_back(i);
        }
        int res = 0, n = pos.size();
        for (int i = 1; i < n; ++i) {
            res = max(res, pos[i] - pos[i - 1]);
        }
        return res;
    }
};



咱们也能够只用一个循环来完成,并且不用 pos 数组,只用一个变量 last 来记录上一个遍历到的 '1' 的位置,初始化为 -1。那么在遍历的过程当中,若遇到了 '1',则判断 last 是否大于等于0,是的话则表示以前已经遇到了 '1',那么当前位置i减去 last,即为两个 '1' 之间的距离,用来更新结果 res,而后再更新 last 为当前位置i,继续遍历便可,参见代码以下:get



解法二:

class Solution {
public:
    int binaryGap(int N) {
        int res = 0, last = -1;
        for (int i = 0; i < 32; ++i) {
            if (((N >> i) & 1) != 0) {
                if (last >= 0) res = max(res, i - last);
                last = i;
            }
        }
        return res;
    }
};



Github 同步地址:

https://github.com/grandyang/leetcode/issues/868



参考资料:

https://leetcode.com/problems/binary-gap/

https://leetcode.com/problems/binary-gap/discuss/149945/Simple-Java-(10-ms)

https://leetcode.com/problems/binary-gap/discuss/149835/C%2B%2BJavaPython-Dividing-by-2



LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索