Note 1

Take Note:

Take a note while surfing.





Note With Ink

Give your Note a Colorful Tag.




Easy to Access

Stay on same information and in Sync wherever you are.

Note 2

Take Note:

Organize your information,It may take Shape.





Think With Ink

Differ your Content by Color.




Easy to Access

Easy to pull up your content from anywhere anytime.

Note 3

Take Note:

Don't Let information to miss,Because it take shape





Note With Ink

Simple an Easy Way to take a note.




Easy to Access

Get the same in next visit.

Program Discussion :: Bitwise Operator
Home > Programs > Bitwise Operator

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

Answer:

#include<iostream>
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<<"\nNo. of set bits :: "<<no_set_bits;
   cout<<endl;
   return 0;
}

Post Your Answer Here:

Name *
Email

Language:

Post Your Reply Here:



Language:

Post Your Reply Here:



Language:

Post Your Reply Here:



Language:

Post Your Reply Here: