basics · intermediate · ~15 min

Count trailing zeros

Count zero bits below the lowest set bit.

Challenge

Implement:

int count_trailing_zeros(uint32_t x);

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

Input format

A 32-bit value.

Output format

Trailing-zero count (0..32).

Constraints

x==0 returns 32.

Starter code

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

Common mistakes

Off-by-one; missing the x==0 special case.

Edge cases to handle

0x100 -> 8; odd numbers -> 0.

Background lessons

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