868. Binary Gap*
https://leetcode.com/problems/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
C++ 实现 1
使用 bitset
库得到数字 N
表示的二进制数, 用 imax
记录两个连续 1
的最大距离, prev
记录前一个 1
的索引, 初始化为 -1
. 遍历二进制数, 如果遇到 1
, 先判断前面是否有 1
, 判断的标准是 prev
是否为 -1
. 如果有, 那么更新距离. 然后更新 prev
. 注意 bitset
的 operator[]
方法返回的是 bool 值.
class Solution {
public:
int binaryGap(int N) {
std::bitset<32> b(N);
int imax = 0, prev = -1;
for (int i = 0; i < b.size(); ++ i) {
if (b[i]) {
if (prev != -1) {
imax = std::max(imax, i - prev);
}
prev = i;
}
}
return imax;
}
};
C++ 实现 2
参考 LeetCode 的官方解答 https://leetcode.com/problems/binary-gap/solution/, 如果不使用 bitset
, 可以使用右移符以及 &
符, 来得到二进制表达.
class Solution {
public:
int binaryGap(int N) {
int last = -1, ans = 0;
for (int i = 0; i < 32; ++i)
if (((N >> i) & 1) > 0) {
if (last >= 0)
ans = std::max(ans, i - last);
last = i;
}
return ans;
}
};