pointers-memory · intermediate · ~10 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.Transfer exercise: apply the lesson to a complete function contract.
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).
This runner exercise assumes 32-bit unsigned int. Return the number of set bits; use unsigned arithmetic and do not mutate caller storage.
int popcount(unsigned int n) { /* TODO */ return 0; }
Using a signed shift or counting only low bits.
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.