[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.

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

Example 1:

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:

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

Example 4:

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:

  • 1 <= N <= 10^9

找一个数的二进制中连续的两个1的最大距离,这里的连续(consecutive)很明显不用相邻,不然也没有最大距离了,两个1之间可以有很多个0

我的做法中规中矩,通过&1来判断最后一位是不是1,第一次碰到1做个记录,第二次碰到1的时候就算出距离并与max比较,最后得到最大的距离

int binaryGap(int N) {
    int max = 0;
    int cur = -1, distance = 0;

    while (N != 0)
    {
        if (N & 1 == 1)
        {
            // 第一次遇到1
            if (cur == -1)
            {
                cur = 1;
            }
            //第二次遇到1,算距离
            else
            {
                max = cur > max ? cur : max;
                cur = 1;
            }
        }
        else
        {
            // 不是0且前面已经遇到1
            if (cur != -1)
            {
                ++cur;
            }
        }

        N = N >> 1;
    }

    return max;
}

看看LeetCode上的其他写法

__builtin_ctz返回一个数二进制位右边第一个1的位置

感觉和我的思路差不多,但代码比我的简洁
直接用内置函数拿到右边第一个1的位置,再遇到一个1的时候就可以直接算距离并和max_distance比较赋值,然后将当前的index设置为last_one

int binaryGap(int N) {
    int max_distance = 0;
    int last_one = __builtin_ctz(N); //右边第一个1的位置
    int test_bit = 1; // 一个mask,用来对二进制的某一位做判断
    int index = 0;

    while(N && test_bit > 0)
    {
        if (N & test_bit)
        {
            max_distance = max(index - last_one, max_distance);
            last_one = index;
        }

        N &= ~test_bit;
        test_bit <<= 1; //修改mask,下一个循环对下一个二进制位做判断
        ++index;
    }

    return max_distance;
}
posted @ 2018-08-09 16:27  arcsinW  阅读(274)  评论(0编辑  收藏  举报