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) |
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
New corrected version.