-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryGap.cpp
More file actions
42 lines (40 loc) · 1020 Bytes
/
BinaryGap.cpp
File metadata and controls
42 lines (40 loc) · 1020 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
40
41
42
#include "all.h"
int solution(int N) {
// write your code in C++14 (g++ 6.2.0)
string binaryRep = "";
while (N > 0) {
if (N%2 == 1) {
binaryRep = "1" + binaryRep;
}else {
binaryRep = "0" + binaryRep;
}
N /= 2;
}
// cout << binaryRep << endl;
vector<int> indices;
for (unsigned int i = 0; i != binaryRep.length(); ++i) {
if (binaryRep[i] == '1') {
indices.push_back(i);
// cout << "index is " << i << endl;
}
}
if (indices.size() <= 1) {
return 0;
}else {
int diff = 0;
int gap = 0;
for (unsigned int i = 0; i != indices.size()-1; ++i) {
gap = indices[i+1] - indices[i];
if (gap > diff) {
diff = gap;
}
}
return diff-1;
}
}
int main(void) {
cout << "Expected 5. Solution gives: " << solution(1041) << endl;
cout << "Expected 0. Solution gives: " << solution(15) << endl;
cout << "Expected 0. Solution gives: " << solution(32) << endl;
return 0;
}