-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path33_binary-gap.cpp
More file actions
39 lines (30 loc) · 897 Bytes
/
33_binary-gap.cpp
File metadata and controls
39 lines (30 loc) · 897 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
int binaryGap(int n) {
bitset<32> bin(n);
int start = 0;
for(int i = 31; i >= 0; i--) {
if(bin[i] == 1) {
start = i;
break;
}
}
cout << bin << endl;
cout << "start: " << start << endl;
int ans = 0;
if(__builtin_popcount(n) < 2) return ans;
for(int i=start; i>=0; i--){
if(bin[i] == 1){
int tempStart = i-1;
// int tempAns = 0;
while((tempStart >= 0) && (bin[tempStart] != 1)){
tempStart--;
}
if(tempStart >= 0) // only update if a valid 1 exists to the left
ans = max(ans, i - tempStart);
}
}
cout << "ans: " << ans << endl;
return ans;
}
};