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
Here are my attempts https://code.sololearn.com/cD67fhI3wbl8/?ref=app
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:])]))
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.
I like your solution rodwynnejones I did not think of that option. Quick solution and with good performance.