I want to write a recursive method function that takes a nonnegative integer n as input and returns the number of 1s in the binary representation on n. I am instructed to use the fact that this is equal to the number of 1s in the representation of n//2 (integer division), plus 1 if n is odd.
Usage:
>>> ones(0)
0
>>> ones(1)
1
>>> ones(14)
3
ok so this is the code I got so far, it still doesn't work though. it gives me 0 no matter what I input as n.
def numOnes(n):
# base case
if n==0:
print (0)
elif n ==1:
print (1)
# recursive case
else:
return numOnes(n//2)+numOnes(n%2)
Thank you
bin(n).count('1'). Do you know it? There is no reasons to make it recursive. Anyway, you should try something yourself.