Take FREE!! Online Mettl Mock Test to Crack TechM and Other Companies Written Exams.
Get Off-Campus Placement Jobs Info !!!
TCS NQT Technical and Managerial Round Interview Questions

Program Discussion :: Bitwise Operator

Home > Programs > Bitwise Operator

1 / 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: