#include <stdio.h>
int countSetBits(unsigned int n) {
int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
int main() {
int n;
scanf("%d", &n);
printf("%d\n", countSetBits(n));
return 0;
}
Explanation:
We check the least significant bit (LSB) using n & 1.
Shift n right by 1 (n >>= 1) to process the next bit.
Repeat until n becomes 0.
If N is negative, its 2’s complement representation will be used, so consider handling it accordingly.