basics · beginner · ~15 min
Use the x & (x-1) trick to test for a single set bit.
Decide whether an unsigned integer is an exact power of two.
Implement int is_power_of_two(unsigned x) that returns 1 if x is a power of two (1, 2, 4, 8, 16, ...) and 0 otherwise. A power of two has exactly one bit set. 0 is not a power of two. No main — the grader calls it.
A single unsigned x.
Returns 1 if x is a power of two, otherwise 0.
is_power_of_two(1) -> 1
is_power_of_two(2) -> 1
is_power_of_two(1024) -> 1
is_power_of_two(3) -> 0
is_power_of_two(0) -> 0
x == 0 returns 0 (no bits set).1 (= 2^0) is a power of two.x && !(x & (x-1)) trick checks for a single set bit without a loop.A single unsigned x.
1 if x is a power of two, otherwise 0.
0 is not a power of two.
int is_power_of_two(unsigned x) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.