The Wayback Machine - https://web.archive.org/web/20240717181821/https://www.geeksforgeeks.org/count-set-bits-of-number-using-recursion/
Open In App

Count Set-bits of number using Recursion

Last Updated : 17 Nov, 2021
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Given a number N. The task is to find the number of set bits in its binary representation using recursion.

Examples: 

Input : 21 
Output : 3 
21 represented as 10101 in binary representation

Input : 16 
Output : 1 
16 represented as 10000 in binary representation 

Approach:  

  1. First, check the LSB of the number.
  2. If the LSB is 1, then we add 1 to our answer and divide the number by 2.
  3. If the LSB is 0, we add 0 to our answer and divide the number by 2.
  4. Then we recursively follow step (1) until the number is greater than 0.

Below is the implementation of the above approach :  

C++




// CPP program to find number
// of set bist in a number
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to find
// number of set bist in a number
int CountSetBits(int n)
{
    // Base condition
    if (n == 0)
        return 0;
         
    // If Least significant bit is set
    if((n & 1) == 1)
        return 1 + CountSetBits(n >> 1);
     
    // If Least significant bit is not set
    else
        return CountSetBits(n >> 1);
}
 
// Driver code
int main()
{
    int n = 21;
     
    // Function call
    cout << CountSetBits(n) << endl;
 
    return 0;
}


Java




// Java program to find number
// of set bist in a number
class GFG
{
    // Recursive function to find
    // number of set bist in a number
    static int CountSetBits(int n)
    {
        // Base condition
        if (n == 0)
            return 0;
             
        // If Least significant bit is set
        if((n & 1) == 1)
            return 1 + CountSetBits(n >> 1);
         
        // If Least significant bit is not set
        else
            return CountSetBits(n >> 1);
    }
     
    // Driver code
    public static void main (String [] args)
    {
        int n = 21;
         
        // Function call
        System.out.println(CountSetBits(n));
    }
}
 
// This code is contributed by ihritik


Python3




# Python3 program to find number
# of set bist in a number
 
# Recursive function to find
# number of set bist in a number
def CountSetBits(n):
     
    # Base condition
    if (n == 0):
        return 0;
         
    # If Least significant bit is set
    if((n & 1) == 1):
        return 1 + CountSetBits(n >> 1);
     
    # If Least significant bit is not set
    else:
        return CountSetBits(n >> 1);
 
# Driver code
if __name__ == '__main__':
    n = 21;
     
    # Function call
    print(CountSetBits(n));
 
# This code is contributed by 29AjayKumar


C#




// C# program to find number
// of set bist in a number
using System;
 
class GFG
{
    // Recursive function to find
    // number of set bist in a number
    static int CountSetBits(int n)
    {
        // Base condition
        if (n == 0)
            return 0;
             
        // If Least significant bit is set
        if((n & 1) == 1)
            return 1 + CountSetBits(n >> 1);
         
        // If Least significant bit is not set
        else
            return CountSetBits(n >> 1);
    }
     
    // Driver code
    public static void Main ()
    {
        int n = 21;
         
        // Function call
        Console.WriteLine(CountSetBits(n));
    }
}
 
// This code is contributed by ihritik


Javascript




<script>
 
// Javascript program to find number
// of set bist in a number
 
// Recursive function to find
// number of set bist in a number
function CountSetBits(n)
{
     
    // Base condition
    if (n == 0)
        return 0;
         
    // If Least significant bit is set
    if ((n & 1) == 1)
        return 1 + CountSetBits(n >> 1);
     
    // If Least significant bit is not set
    else
        return CountSetBits(n >> 1);
}
 
// Driver code
var n = 21;
 
// Function call
document.write(CountSetBits(n));
 
// This code is contributed by Amit Katiyar
 
</script>


Output: 

3

 

Time Complexity: O(log n)

Auxiliary Space: O(log n)



Previous Article
Next Article

Similar Reads

Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X &amp; Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X &amp; Y) = M, where ⊕ denotes the Bitwise XOR and &amp; denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n &gt; 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Flip bits of the sum of count of set bits of two given numbers
Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representation of the sum obtained = 101Flipping the bits of th
5 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most N/2. Examples: Input: S = "1010001"Output: 3Expla
12 min read
Print numbers having first and last bits as the only set bits
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.Examples: Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2 Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i. C
10 min read
Toggle bits of a number except first and last bits
Given a number, the task is to toggle bits of the number except the first and the last bit.Examples: Input : 10 Output : 12 Binary representation:- 1 0 1 0 After toggling first and last : 1 1 0 0 Input : 9 Output : 15 Binary representation : 1 0 0 1 After toggling first and last : 1 1 1 1 Prerequisite: Find most significant set bit of a number Gene
8 min read
Count number of set bits in a range using bitset
Given a large binary number.The task is to count the number of 1's in a given range from L to R (1 based indexing).Examples: Input : s = "101101011010100000111", L = 6, R = 15 Output : 5 s [L : R] = "1011010100" There is only 5 set bits.Input : s = "10110", L = 2, R = 5 Output : 2 Approach: Convert the string of size len to the bitset of size N.The
5 min read
Check if all bits can be made same by flipping two consecutive bits
Given a binary string, the task is to find whether all the digits of the string can be made equal i.e either 0 or 1 by flipping two consecutive bits any number of times.Examples: Input: 01011Output: YESExplanation:Flip 2nd and 3rd bit -&gt; 00111, again flipping 1'st and 2'nd bit -&gt; 11111 Input: 100011Output: NOExplanation:No number of moves can
5 min read
Count positions in Binary Matrix having equal count of set bits in corresponding row and column
Given a boolean matrix mat[][] of size M * N, the task is to print the count of indices from the matrix whose corresponding row and column contain an equal number of set bits. Examples: Input; mat[][] = {{0, 1}, {1, 1}}Output: 2Explanation:Position (0, 0) contains 1 set bit in corresponding row {(0, 0), (0, 1)} and column {(0, 0), (1, 0)}.Position
10 min read
Practice Tags :
three90RightbarBannerImg