Last active
June 26, 2021 06:30
-
-
Save bact/9868225897ae98c486f7c70d740b062b to your computer and use it in GitHub Desktop.
find binary gap using regular expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
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
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.)