#include <stdio.h>
int countSetBits(unsigned int n) {
// Write your code here
int theCount=0;
while (n != 0) {
theCount += (n & 1);
n >>= 1;
}
return theCount;
}
int main() {
int n;
scanf("%d", &n);
printf("%d", countSetBits(n));
return 0;
}
Solving Approach
Count the bits by bitwise AND with ONE , bit 0, then shift right by one bit until no more set bits.