-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryGap868.cpp
More file actions
54 lines (52 loc) · 1.32 KB
/
binaryGap868.cpp
File metadata and controls
54 lines (52 loc) · 1.32 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public:
int binaryGap(int N) {
vector<bool>one(31,false);
int digit;
for (int i = 0; i < 31; i++) {
digit = N>>i;
if (digit&1 == 1) {
//cout << i <<" , ";
one[i] = true;
}
}
int ans = 0;
for (int i = 0; i < 31; i++) {
if (one[i]) {
for (int j = i+1; j < 31; j++) {
if (one[j]) {
ans = max (ans, j-i);
break;
}
}
}
}
return ans;
}
};
//the fatest method
class Solution {
public:
int binaryGap(int N) {
bitset<64> bs(N);
//cout << bs.to_string() << endl;
bool bStart = false;
int nPrev = 0;
int nMax = 0;
for(int i = 0; i < 64; i++) {
if(!bStart && bs[i] == true) {
bStart = true;
nPrev = i;
continue; //get rid of the case where first 1 bit is the only 1 bit
}
if(!bStart) {
continue;
}
if(bs[i] == true) {
nMax = max(i - nPrev, nMax);
nPrev = i;
}
}
return nMax;
}
};