跳转至

868. 二进制间距

题目描述

给定一个正整数 n,找到并返回 n 的二进制表示中两个 相邻 1 之间的 最长距离 。如果不存在两个相邻的 1,返回 0

如果只有 0 将两个 1 分隔开(可能不存在 0 ),则认为这两个 1 彼此 相邻 。两个 1 之间的距离是它们的二进制表示中位置的绝对差。例如,"1001" 中的两个 1 的距离为 3 。

 

示例 1:

输入:n = 22
输出:2
解释:22 的二进制是 "10110" 。
在 22 的二进制表示中,有三个 1,组成两对相邻的 1 。
第一对相邻的 1 中,两个 1 之间的距离为 2 。
第二对相邻的 1 中,两个 1 之间的距离为 1 。
答案取两个距离之中最大的,也就是 2 。

示例 2:

输入:n = 8
输出:0
解释:8 的二进制是 "1000" 。
在 8 的二进制表示中没有相邻的两个 1,所以返回 0 。

示例 3:

输入:n = 5
输出:2
解释:5 的二进制是 "101" 。

 

提示:

  • 1 <= n <= 109

解法

方法一

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def binaryGap(self, n: int) -> int:
        ans, j = 0, -1
        for i in range(32):
            if n & 1:
                if j != -1:
                    ans = max(ans, i - j)
                j = i
            n >>= 1
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
    public int binaryGap(int n) {
        int ans = 0;
        for (int i = 0, j = -1; n != 0; ++i, n >>= 1) {
            if ((n & 1) == 1) {
                if (j != -1) {
                    ans = Math.max(ans, i - j);
                }
                j = i;
            }
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
public:
    int binaryGap(int n) {
        int ans = 0;
        for (int i = 0, j = -1; n; ++i, n >>= 1) {
            if (n & 1) {
                if (j != -1) ans = max(ans, i - j);
                j = i;
            }
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func binaryGap(n int) int {
    ans := 0
    for i, j := 0, -1; n != 0; i, n = i+1, n>>1 {
        if (n & 1) == 1 {
            if j != -1 && ans < i-j {
                ans = i - j
            }
            j = i
        }
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function binaryGap(n: number): number {
    let res = 0;
    let j = -1;
    for (let i = 0; n !== 0; i++) {
        if (n & 1) {
            if (j !== -1) {
                res = Math.max(res, i - j);
            }
            j = i;
        }
        n >>= 1;
    }
    return res;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
impl Solution {
    pub fn binary_gap(mut n: i32) -> i32 {
        let mut res = 0;
        let mut i = 0;
        let mut j = -1;
        while n != 0 {
            if (n & 1) == 1 {
                if j != -1 {
                    res = res.max(i - j);
                }
                j = i;
            }
            n >>= 1;
            i += 1;
        }
        res
    }
}

评论