In: Computer Science
PYTHON 3:
Write a recursive function that takes a non-negative integer n as input and returns the number of 1's in the binary representation of n.
Use the fact that this is equal to the number of 1's in the representation of n//2 (integer division) plus 1 if n is odd.
>>>numOnes(0) 0 >>>numOnes(1) 1 >>>numOnes(14) 3
def numOnes(n): #function
if n==0:
return (0) #base cases
elif n == 1:
return (1)
else:
return numOnes(n//2)+numOnes(n%2) #recursive call
print(numOnes(0))
print(numOnes(1))
print(numOnes(14))
output: