Skip to content

Instantly share code, notes, and snippets.

@bact
Last active June 26, 2021 06:30
Show Gist options
  • 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)
@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