All submissions

Count Set Bits in an Integer

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    unsigned int count = 0;
    while(n) {
        count += n & 1;
        n >>= 1;
    }
    return count;
}

int main() {
    int n;
    scanf("%d", &n);
    printf("%d", countSetBits(n));
    return 0;
}

Solving Approach

In the countSetBits function, we define an unsigned int count which counts the number of set bits in the given integer. 

We then do bitwise AND'ing of each bit in n while iterating through it. 
if n & 1 == 1, we get count + 1

We then right shift n

 

 

Loading...

Input

5

Expected Output

2