forked from markhary/codility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryGap.cpp
35 lines (30 loc) · 834 Bytes
/
BinaryGap.cpp
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
// https://app.codility.com/programmers/lessons/1-iterations/binary_gap/
//
// Task Score: 100%
// Correctness: 100%
// Performance: Not assessed
//
#include <cmath>
int solution(int N) {
int numBits = floor(std::log2(N))+1;
bool foundOne = false;
int maximumGap = 0;
int possibleGap = 0;
for (int i=0; i<numBits; i++) {
// find a 0
if ( foundOne && !(N & (1<<i))) {
possibleGap++;
} else if ((N & (1<<i))) {
// If we found a one, set the gap length and reset the
// current counter
if (foundOne) {
if (possibleGap > maximumGap) {
maximumGap = possibleGap;
}
possibleGap = 0;
}
foundOne = true;
}
}
return maximumGap;
}