basics · beginner · ~15 min
Detect values with exactly one bit set.
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.
x.
1 if power of two, else 0.
0 returns 0.
#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; }
Forgetting the x != 0 guard (0 would wrongly pass x & (x-1) == 0).
1, 2, 4, ... are powers of two; 0 and 3 are not.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.