basics · intermediate · ~15 min

Count leading zeros

Count zero bits above the highest set bit.

Challenge

Implement:

int count_leading_zeros(uint32_t x);

Return the number of leading (most-significant) zero bits. Return 32 if x==0.

Input format

A 32-bit value.

Output format

Leading-zero count (0..32).

Constraints

x==0 returns 32.

Starter code

#include <stdint.h>
/* Number of leading zero bits in a 32-bit value (32 if x==0). */
int count_leading_zeros(uint32_t x){ (void)x; return 0; }

Common mistakes

Looping forever on x==0; not handling the all-zero case explicitly.

Edge cases to handle

0x80000000 -> 0; 1 -> 31.

Background lessons

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