868. 二进制间距
为保证权益,题目请参考 868. 二进制间距(From LeetCode).
解决方案1
CPP
C++
#include <algorithm>
using namespace std;
class Solution {
public:
int binaryGap(int n) {
int maxDistance = 0;
int prevIdx = -1;
for (int i = 0; i < 32; i++) {
if (n & (1 << i)) {
if (prevIdx == -1) {
prevIdx = i;
} else {
maxDistance = max(maxDistance, i - prevIdx);
prevIdx = i;
}
}
}
return maxDistance;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23