+ 2

Binary gap

Given a positive integer, calculate the maximum distance between 1 in binary representation. For example number 9 has a gap of 2 because its binary representation is 1001. This is my proposed algorithm: Any suggestions to improve it? https://code.sololearn.com/ckupsnCs632F/?ref=app

2nd Mar 2020, 10:00 PM
GeraltdeRivia
5 Answers
2nd Mar 2020, 10:29 PM
Gabriel Ilie
Gabriel Ilie - avatar
+ 2
import re # version 1. using a function def max_distance(s): return max([len(x) for x in re.findall(r"0+", bin(s)[2:])]) print(max_distance(int(input("input a number:- ")))) # version 2 , as a one liner print(max([len(x) for x in re.findall(r"0+", bin(int(input("input a number:- ")))[2:])]))
2nd Mar 2020, 11:26 PM
rodwynnejones
rodwynnejones - avatar
+ 1
use re.findall to pull all the '0' as a list. use list comprehension and len function on each item the findall returns to fill that list... use the max function on that list. 4 lines of code (if you include the import and def a function) Can also be done as a one liner (2 lines if you include the import statement.
2nd Mar 2020, 10:32 PM
rodwynnejones
rodwynnejones - avatar
+ 1
I like your solution rodwynnejones I did not think of that option. Quick solution and with good performance.
2nd Mar 2020, 10:36 PM
GeraltdeRivia
2nd Mar 2020, 11:15 PM
Vitaly Sokol
Vitaly Sokol - avatar