#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; }
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
countSetBits
count
We then right shift n
Test Cases
Test Results
Input
5
Expected Output
2