I am new at programming (please be nice :)) and I am trying to write a function that calculates the binary gap of a number using recursion by using the modulus function to gather the bits of an integer and then counting the number of 0s between 1s and displaying the longest chain 0s in between two 1s.
For example
Input = 10, Binary value = 1010, Binary Gap = 1
Input = 15, Binary value = 1111, Binary Gap = 0
Input = 41, Binary value = 101001, Binary Gap = 2
As it stands the code below will always return a 0 if an even number is inputted and always throw a recursion error should an odd number be used. This leads me to believe there is a problem involving the division and it being stuck in an infinite loop but cannot figure out why.
def binary_gap(n, foundFirstOne= False, numofZeros= 0):
if n == 0:
return 0
bit = n % 2
if bit == 1:
ans = binary_gap((n / 2), True, 0)
else:
if foundFirstOne == True:
ans = binary_gap((n / 2), True, numofZeros+1)
else:
ans = binary_gap((n / 2), False, 0)
return ans and numofZeros
print(binary_gap(int(input("Please enter a number"))))