Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with bit manipulation with longest binary gap? [duplicate]

Tags:

python

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?

like image 808
Richard Rublev Avatar asked Nov 17 '25 13:11

Richard Rublev


1 Answers

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
like image 131
oppressionslayer Avatar answered Nov 20 '25 03:11

oppressionslayer