30. Count Set Bits in an Integer

Back To All Submissions
Previous Submission
Next Submission

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

 

 

Was this helpful?
Upvote
Downvote