Jan-04-2021, 02:34 PM
Hi I'm trying to write a code to give the biggest gap in a binary number. Here's my code:
N = int(input("Please enter an integer:")) def binary_gap(N): binary = str(bin(N))[2:] bin_gap = False bin_max = 0 bin_counter = 0 for num in binary: if num == 1: if bin_max < bin_counter: # if the current gap is bigger than the largest recorded gap set this gap as bin_max bin_max = bin_counter bin_gap = True elif bin_gap: # adds 1 to the counter total. bin_counter += 1 print(binary) print(f"The largest binary gap in {N} is {bin_counter}") binary_gap(N)And here's the output that I'm getting:
Output:Please enter an integer:45
101101
The largest binary gap in 45 is 0
I'm not sure why its giving me zero as I'm printing the binary number and I can see that the answer should be 1.