Skip to content

Instantly share code, notes, and snippets.

@bact
Last active June 26, 2021 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bact/9868225897ae98c486f7c70d740b062b to your computer and use it in GitHub Desktop.
Save bact/9868225897ae98c486f7c70d740b062b to your computer and use it in GitHub Desktop.
find binary gap using regular expression
import re
def bingap(num): # wronggggg
zeroes = re.findall(r"0+", bin(num)[2:])
return len(max(zeroes, key=len)) if zeroes else 0
n = 32
print(bin(n))
bingap(n)
@bact
Copy link
Author

bact commented Sep 22, 2018

This code is actually wrong - -" Bad interpretation of the question.

Binary gap definition is those 0s between two 1s.

This code find the longest running 0s, but they are not necessary being terminated with 1.

ex.
For input 0b100, it will return 2. Which is wrong, as there's no terminating 1 after final 0.
It should return 0, as there is no gap found.)

@bact
Copy link
Author

bact commented Sep 23, 2018

New corrected version.

import re

def bingap(num):
    zeroes = re.findall(r"0+(?=1)", bin(num)[2:])
    return len(max(zeroes, key=len)) if zeroes else 0

@alexisbenitez
Copy link

I would add the lookbehind (?<=1) at the beggining, since otherwise you are getting one extra number (the first 1 of each match):

import re

def solution(N):
    zeros = re.findall(r'(?<=1)0+(?=1)', str(bin(N))[2:])
    return len(max(zeros)) if zeros else 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment