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:
- 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 :
C++
#include <bits/stdc++.h>
using namespace std;
int CountSetBits(int n)
{
if (n == 0)
return 0;
if((n & 1) == 1)
return 1 + CountSetBits(n >> 1);
else
return CountSetBits(n >> 1);
}
int main()
{
int n = 21;
cout << CountSetBits(n) << endl;
return 0;
}
|
Java
class GFG
{
static int CountSetBits(int n)
{
if (n == 0)
return 0;
if((n & 1) == 1)
return 1 + CountSetBits(n >> 1);
else
return CountSetBits(n >> 1);
}
public static void main (String [] args)
{
int n = 21;
System.out.println(CountSetBits(n));
}
}
|
Python3
def CountSetBits(n):
if (n == 0):
return 0;
if((n & 1) == 1):
return 1 + CountSetBits(n >> 1);
else:
return CountSetBits(n >> 1);
if __name__ == '__main__':
n = 21;
print(CountSetBits(n));
|
C#
using System;
class GFG
{
static int CountSetBits(int n)
{
if (n == 0)
return 0;
if((n & 1) == 1)
return 1 + CountSetBits(n >> 1);
else
return CountSetBits(n >> 1);
}
public static void Main ()
{
int n = 21;
Console.WriteLine(CountSetBits(n));
}
}
|
Javascript
<script>
function CountSetBits(n)
{
if (n == 0)
return 0;
if ((n & 1) == 1)
return 1 + CountSetBits(n >> 1);
else
return CountSetBits(n >> 1);
}
var n = 21;
document.write(CountSetBits(n));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(log n)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
17 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...