DEV Community

Bernice Waweru
Bernice Waweru

Posted on • Updated on

Binary Gap

Instructions

Find longest sequence of zeros in binary representation of an integer.

Example

n=32 
output = 0 because binary representation of 32 is '100000' and thus no binary gaps.
n = 1041
output = 5, because binary representation of 32 is 10000010001.

Enter fullscreen mode Exit fullscreen mode

Approach

We convert the integer to binary representation and strip the 0's at the end because they do not affect our output.
We then split the binary at 1's and determine the max number of continuous zeros.

Python Implementation

def gap(n):
    b = bin(n)[2:]
    b = b.strip("0")
    l = b.split("1")
    return len(max(l, key=len))
Enter fullscreen mode Exit fullscreen mode

The max function takes an iterable l which consists of zeros and a function as a key to determine the max value based on length.

Note we supply key= len and not key=len()

That's all for today.

Latest comments (0)