basics · beginner · ~15 min

Is it a power of two?

Detect values with exactly one bit set.

Challenge

Implement:

int is_power_of_two(unsigned x);

Return 1 if x has exactly one bit set (a power of two), else 0. Note: 0 is not a power of two.

Input format

x.

Output format

1 if power of two, else 0.

Constraints

0 returns 0.

Starter code

#include <stddef.h>
/* Return 1 if x has exactly one bit set (a power of two), else 0. Note: 0 is not. */
int is_power_of_two(unsigned x){ (void)x; return 0; }

Common mistakes

Forgetting the x != 0 guard (0 would wrongly pass x & (x-1) == 0).

Edge cases to handle

1, 2, 4, ... are powers of two; 0 and 3 are not.

Background lessons

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