How to Solve the Binary Gap Problem in Python?

Estimated read time 2 min read

The Binary Gap Problem asks you to find the maximum distance between two 1s in the binary representation of a positive integer. Here is an example of how to solve this problem in Python:

def binary_gap(n):
    # convert the integer to binary
    binary = bin(n)[2:]
    # iterate through the binary string and count the gaps between 1s
    max_gap = 0
    gap = 0
    for digit in binary:
        if digit == '1':
            if gap > max_gap:
                max_gap = gap
            gap = 0
        else:
            gap += 1
    return max_gap

# test the function with a sample input
n = 1041
print(binary_gap(n))

In this solution, we define a function binary_gap that takes a positive integer n as input. The function first converts the integer to binary using the built-in bin function and slices off the first two characters (‘0b’) to obtain the binary string.

The function then iterates through the binary string and counts the number of zeros between two ones. If a one is encountered, the function updates the maximum gap seen so far, resets the gap counter to zero, and continues iterating. If a zero is encountered, the gap counter is incremented.

After iterating through the binary string, the function returns the maximum gap seen between two ones.

In the main part of the script, we test the function with a sample input integer n and print out the result.

To use this code with other inputs, simply replace n with the desired input integer.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply