Here we will see how we can check number of set bits in an integer number. The set bits are 1’s in the binary representation of a number. For an example the number 13 has three set bits 1101. So the count will be 3.
To solve this problem, we will shift the number to the right, and if the LSb is 1, then increase count. Until the number becomes 0, it will run.
Algorithm
countSetBit()
begin count := 0 while count is not 0, do if LSb of n is set, then count := count + 1 end if n := n after shifting 1 bit to right done return count end
Example
#include<iostream> using namespace std; int count_set_bit(int n) { int count = 0; while(n != 0) { if(n & 1 == 1) { count++; } n = n >> 1; //right shift 1 bit } return count; } int main() { int n; cout << "Enter a number: "; cin >> n; cout << "Number of set bits: " << count_set_bit(n); }
Output
Enter a number: 29 Number of set bits: 4
This program will run in C and generates output, but when we want to compile in C++, it will return an error during compile time. It will say there are too many arguments are passed.