Count Set Bits in an Integer

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    const int NB_BITS = sizeof(int) * 8;
    int cnt = 0;
    for (int i = 0; i < NB_BITS; i++) {
        cnt += (n & 1);
        n >>= 1; 
    }
    return cnt;
}

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

Solving Approach

a variant using sizeof()

 

 

Upvote
Downvote
Loading...

Input

5

Expected Output

2