[Updated] Goldman Sachs Aptitude Test Questions and Answers
Practice List of TCS Digital Coding Questions !!!
Take 50+ FREE!! Online Data Interpretation Mock test to crack any Exams.

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: