basics · intermediate · ~15 min

Compute parity

Return whether the number of set bits is odd.

Challenge

Implement:

int parity(unsigned x);

Return 1 if x has an odd number of set bits, else 0.

Input format

x.

Output format

1 for odd popcount, else 0.

Constraints

None.

Starter code

#include <stddef.h>
/* Return 1 if x has an odd number of set bits, else 0. */
int parity(unsigned x){ (void)x; return 0; }

Common mistakes

Returning the popcount itself instead of its low bit.

Edge cases to handle

0 -> 0; 7 (three bits) -> 1.

Background lessons

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