868. 二进制间距『简单』

题目来源于力扣(LeetCode

一、题目

868. 二进制间距

题目相关标签:数学

提示:

  • 1 <= N <= 10^9

二、解题思路

  1. 循环对数字 N 进行二进制的舍位,判断最低位是否为 1

  2. 为 1 时,将之间记录的 maxLen 与本次两个 1 间隔的数量比较,取最大值,并将 count 重置为 1

  3. 为 0 时,若 count 不为 0,说明已经记录有二进制 1 的位置,则 count + 1

注意:101,间隔为 2,11,间隔为 1

三、代码实现

public static int binaryGap(int N) {
    int count = 0;
    int maxLen = 0;

    while (N > 0) {
        if ((N & 1) == 1) {
            maxLen = Math.max(maxLen, count);
            count = 1;
        } else {
            if (count > 0) {
                count += 1;
            }
        }
        N = N >> 1;
    }
    return maxLen;
}

四、执行用时

五、部分测试用例

public static void main(String[] args) {
    int n = 22;  // output: 2
//    int n = 5;  // output: 2
//    int n = 6;  // output: 1
//    int n = 8;  // output: 0

    int result = binaryGap(n);
    System.out.println(result);
}
原文地址:https://www.cnblogs.com/zhiyin1209/p/13221892.html