pointers-memory · intermediate · ~15 min

Count set bits (Hamming weight)

Bit-level loops; the n &= (n-1) trick.

Challenge

Count how many bits are set to 1 in an unsigned integer (its "Hamming weight").

Task

Implement int popcount(unsigned int n) that returns the number of 1-bits in the binary representation of n. No main — the grader calls it.

Input

A single unsigned int n (0 to UINT_MAX, i.e. all 32 bits may be set).

Output

Returns the count of set bits as an int (0 to 32).

Example

popcount(0)           ->   0
popcount(7)           ->   3     (binary 111)
popcount(0xFFFFFFFF)  ->   32

Edge cases

  • n == 0 returns 0.
  • All bits set returns 32.

Input format

A single unsigned int n.

Output format

The number of 1-bits in n, as an int (0..32).

Constraints

No library popcount builtins; loop over the bits.

Starter code

int popcount(unsigned int n) { /* TODO */ return 0; }

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