basics · intermediate · ~15 min
Count the 1 bits in a value.
Implement:
int popcount(unsigned x);
Return the number of bits set to 1 in x.
x.
The count of 1 bits (0..32).
None.
#include <stddef.h>
/* Count the number of 1 bits in x. */
int popcount(unsigned x){ (void)x; return 0; }
Infinite loop from a signed right shift; off-by-one on the last bit.
0 has 0 set bits; 0xFFFFFFFF has 32.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.