Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding biggest binary gap

Tags:

python

I have to find the binary gap for an integer number.

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example: N = 1041 binary:10000010001 Result: 5 (5 zeros surrounded by ones)

Below is my code, although bin_no[22] is 1 but it never goes inside if statement.

def solution(N):
    bin_no = f'{N:32b}'
    print(len(bin_no))
    count = []

    for i in range(len(bin_no)):
        if bin_no[i] == 1:
            count[i] = 0
            j=i
            while(bin_no[j+1] != 1):
                count[i] +=1
                j +=1
            print (count[i])

print(solution(529))
like image 339
Sana Avatar asked Feb 18 '26 21:02

Sana


2 Answers

Simple and fast

def solution(N):
    binary = bin(N)[2:].strip("0").split("1")
    return max(len(x) for x in binary)
like image 126
Kwaku Manu Amponsem Avatar answered Feb 20 '26 09:02

Kwaku Manu Amponsem


use regex:

def solution(N):
    bin_no = f'{N:b}'
    pt= r"10+(?=1)"
    mtchs = re. findall(pt, bin_no)
    print(bin_no)
    print(mtchs)
    mx = max(mtchs,key=len)
    return mx.count('0')

print(solution(401))

output:

110010001

['100', '1000']

3

like image 41
moyoumos Avatar answered Feb 20 '26 09:02

moyoumos