Given a number N. The task is to find the number of set bits in its binary representation using recursion.
Input : 21
Output : 3
21 represesnted as 10101 in binray representation
Input : 16
Output : 1
16 represesnted as 10000 in binray representation
- First, check the LSB of the number.
- If the LSB is 1, then we add 1 to our answer and divide the number by 2.
- If the LSB is 0, we add 0 to our answer and divide the number by 2.
- Then we recursively follow step (1) until the number is greater than 0.
Below is the implementation of the above approach :
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Count the occurence of digit K in a given number N using Recursion
- Count of subsets with sum equal to X using Recursion
- Sum of digit of a number using recursion
- Decimal to binary number using recursion
- Program to find all Factors of a Number using recursion
- Add the given digit to a number stored in a linked list using recursion
- How to solve problems related to Number-Digits using Recursion?
- Count number of trailing zeros in Binary representation of a number using Bitset
- Count number of subsets having a particular XOR value
- Count pairs with Bitwise-AND as even number
- Count pairs with Bitwise XOR as EVEN number
- Count pairs with Bitwise OR as Even number
- Count total bits in a number
- Count unset bits of a number
- Count pairs with Bitwise XOR as ODD number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.