I read a little bit and found python-longest-binary-gap SO question
def solution(N):
max_gap = 0
new_gap = 0
for i in range(N.bit_length()):
if N & (1 << i):
if new_gap > max_gap:
max_gap = new_gap
new_gap =0
else:
new_gap += 1
if new_gap > max_gap:
max_gap = new_gap
return max_gap
The problem is that it gives the wrong solution for 32 (5 instead of 0) or 64. How to fix this?
Here's a pandas solution to this problem:
import pandas as pd
def getlargestgap(x):
df = pd.DataFrame(list(map(list, bin(x)[2:])), columns=['A'])
df['B'] = df.groupby(df.A.ne(df.A.shift()).cumsum()).cumcount()+1
df['Truth'] = df['A'] == '0'
return df.loc[df['Truth'] == True]['B'].max()
getlargestgap(23432124)
# 4
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