pointers-memory · intermediate · ~15 min
Bit-level loops; the n &= (n-1) trick.
Count how many bits are set to 1 in an unsigned integer (its "Hamming weight").
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.
A single unsigned int n (0 to UINT_MAX, i.e. all 32 bits may be set).
Returns the count of set bits as an int (0 to 32).
popcount(0) -> 0
popcount(7) -> 3 (binary 111)
popcount(0xFFFFFFFF) -> 32
n == 0 returns 0.A single unsigned int n.
The number of 1-bits in n, as an int (0..32).
No library popcount builtins; loop over the bits.
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.