pointers-memory · intermediate · ~10 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.

Why this matters

Transfer exercise: apply the lesson to a complete function contract.

Input format

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

Output format

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

Constraints

This runner exercise assumes 32-bit unsigned int. Return the number of set bits; use unsigned arithmetic and do not mutate caller storage.

Starter code

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

Common mistakes

Using a signed shift or counting only low bits.

Edge cases to handle

Zero; one high bit; all bits set; alternating bits.

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