Binary Gap

wanguiwaweru

Bernice Waweru

Posted on February 25, 2022

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.

💖 💪 🙅 🚩
wanguiwaweru
Bernice Waweru

Posted on February 25, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related