Get Off-Campus Placement Jobs Info !!!
Programs asked in Mettl Coding Round
Click To Practce List of Programs asked in Nagarro !!!

Program Discussion :: Bitwise Operator

Home > Programs > Bitwise Operator

12 / 15

Write an efficient program to count the number of bits set in an integer number

Answer:

#include
using namespace std;

// count the no. of set bits in a positive integer
int countSetBits(unsigned int num) {
   unsigned int count = 0;
   while (num) {
      // bitwise AND operation to check if the
      // leftmost bit is set or not
      // if set, increment the count
      count += num & 1;
      // left shift the nm by one position
      num >>= 1;
   }
   return count;
}

//main
int main() {
   unsigned int num = 6;
   unsigned int no_set_bits = countSetBits(num);
   cout

Asked In ::

Post Your Answer Here:

Language:

Post Your Reply Here:



Language:

Post Your Reply Here:



Language:

Post Your Reply Here:



Language:

Post Your Reply Here:



Language:

Post Your Reply Here: