Calculate number of set bits in integer n

 

#include <iostream> 
using namespace std;

//function to calculate number of set bit of an integer n
unsigned isolateRightMostSetBit(unsigned int n)
{
unsigned int count = 0;
while(n){
n &= n-1;
count ++;
}
return count;
}

int main()
{
unsigned int n = 7;
unsigned int result = isolateRightMostSetBit(n);
cout << "Number of set bits in integer "<< n << ", we get "<< result<<"." << endl;
return 0;
}

Comments

Popular posts from this blog

Clear right most set bit of an integer n

Swap bits at ith and jth position of integer n

Toggle the bit at Kth position of integer n