Given a positive integer n, the task is to find the number of set bits in its binary representation using recursion.
Examples:
Input : 21
Output : 3
Explanation: 21 represented as 10101 in binary representation.Input : 16
Output : 1
Explanation: 16 represented as 10000 in binary representation.
Using Recursion and Right Shift Operator - O(log n) time and O(log n) space
The idea is to recursively check the least significant bit in the number. If the bit is 1, increment the result. Right shift the number by 1, and recursively find the number of set bits in the computed number.
Step by step approach:
- Recursively check the least significant bit of a number. Base case will return 0 if number is 0.
- If the least significant bit is 1, add 1 to result.
- Right shift the number by 1, to remove the least significant bit and recursively find the number of set bits in the computed number.
// C++ 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 setBits(int n) {
// Base condition
if (n == 0)
return 0;
// If Least significant bit is set
if((n & 1) == 1)
return 1 + setBits(n >> 1);
// If Least significant bit is not set
else
return setBits(n >> 1);
}
int main() {
int n = 21;
cout << setBits(n) << endl;
return 0;
}
// Java program to find number
// of set bits in a number
class GfG {
// Recursive function to find
// number of set bits in a number
static int setBits(int n) {
// Base condition
if (n == 0)
return 0;
// If Least significant bit is set
if((n & 1) == 1)
return 1 + setBits(n >> 1);
// If Least significant bit is not set
else
return setBits(n >> 1);
}
public static void main(String[] args) {
int n = 21;
System.out.println(setBits(n));
}
}
# Python program to find number
# of set bits in a number
# Recursive function to find
# number of set bits in a number
def setBits(n):
# Base condition
if n == 0:
return 0
# If Least significant bit is set
if (n & 1) == 1:
return 1 + setBits(n >> 1)
# If Least significant bit is not set
else:
return setBits(n >> 1)
if __name__ == "__main__":
n = 21
print(setBits(n))
// C# program to find number
// of set bits in a number
using System;
class GfG {
// Recursive function to find
// number of set bits in a number
static int setBits(int n) {
// Base condition
if (n == 0)
return 0;
// If Least significant bit is set
if((n & 1) == 1)
return 1 + setBits(n >> 1);
// If Least significant bit is not set
else
return setBits(n >> 1);
}
static void Main() {
int n = 21;
Console.WriteLine(setBits(n));
}
}
// JavaScript program to find number
// of set bits in a number
// Recursive function to find
// number of set bits in a number
function setBits(n) {
// Base condition
if (n === 0)
return 0;
// If Least significant bit is set
if((n & 1) === 1)
return 1 + setBits(n >> 1);
// If Least significant bit is not set
else
return setBits(n >> 1);
}
let n = 21;
console.log(setBits(n));
Output
3
Related Article: