156k views
3 votes
Write a recursive function that returns the number of 1 in the binary representation of N. Use the fact that this is equal to the number of 1 in the representation of N/2, plus 1, if N is odd.

User Emher
by
5.6k points

1 Answer

5 votes

Answer:

#here is code in python

# recursive function that counts the number of 1's

def bin_count(num):

#base condition

if num==0:

return (0)

elif num == 1:

return (1)

else:

#recursive call

return bin_count(num//2)+bin_count(num%2)

#read a number

num=int(input("enter a number:"))

#call the function

print("number of 1's is:",bin_count(num))

Step-by-step explanation:

Read a number from user and call the function bin_count() with parameter num. In the function, if num=0 then it will return 0.If num is 1 then return 1 else it will count the number of 1's inn the binary representation of the number and return the count.

Output:

enter a number:63

number of 1's is: 6

User Matin Petrulak
by
6.4k points