basics · intermediate · ~15 min

Count set bits (popcount)

Count the 1 bits in a value.

Challenge

Implement:

int popcount(unsigned x);

Return the number of bits set to 1 in x.

Input format

x.

Output format

The count of 1 bits (0..32).

Constraints

None.

Starter code

#include <stddef.h>
/* Count the number of 1 bits in x. */
int popcount(unsigned x){ (void)x; return 0; }

Common mistakes

Infinite loop from a signed right shift; off-by-one on the last bit.

Edge cases to handle

0 has 0 set bits; 0xFFFFFFFF has 32.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.