Skip to content

Instantly share code, notes, and snippets.

@divmgl
Last active April 8, 2017 09:48
Show Gist options
  • Save divmgl/766af75c2c6abe24d457edbc888cd45a to your computer and use it in GitHub Desktop.
Save divmgl/766af75c2c6abe24d457edbc888cd45a to your computer and use it in GitHub Desktop.
Codility.com BinaryGap 100%
def solution(N):
max = 0
bits = 0
bin = "{0:b}".format(N)
for c in bin:
if c == "0":
bits += 1
if c == "1":
if max < bits:
max = bits
bits = 0
return max
@divmgl
Copy link
Author

divmgl commented Apr 8, 2017

The solution in C:

int solution(int n) {
    int k = n;
    int max = 0;
    int bits = 0;
    int cursor = 0;
    int started = 0;
    
    while (k > 0) {
        cursor = k & 1;
        if (cursor == 0 && started == 1) { bits += 1; }
        if (cursor == 1) {
            started = 1;
            if (max < bits) { max = bits; }
            bits = 0;
        }
        k >>= 1;
    }
    
    return max;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment