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))
Simple and fast
def solution(N):
binary = bin(N)[2:].strip("0").split("1")
return max(len(x) for x in binary)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With