C/C++ Program to the Count set bits in an integer?


Counting set bits means counting 1’S of the given integer. For this, we have multiple solutions that can be applied. For this case, we have a binary number( binary representation of an integer), for which we have to count the number of 1’s off the string.

To count the number of 1’s, we will take the string, traverse each element and count all the 1’s of the string. For example, if we input 17 the output will be 2 because the binary of 17 is 10001 that contains two 1's.

Input: Enter a positive integer: 6
Output: 2

Explanation

The binary representation of 6 is 110 which has 2 set bits

This iterative approach requires one iteration per bit. It runs through all the bits of the number. Iteration terminates when no more bits are set. In the worst case, on a 32-bit word with only the most significant bit set, it will loop through 32 iterations. This solution is the simplest one and useful if 1's are sparse and among the least significant bits.

Example

#include <stdio.h>
int main(void) {
   unsigned int n = 34;
   for (c = 0; n; n >>= 1) {
      c += n & 1;
   }
   printf("%d\n", c);
}

Updated on: 19-Aug-2019

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements