basics · beginner · ~15 min

Is a number a power of two?

Use the x & (x-1) trick to test for a single set bit.

Challenge

Implement int is_power_of_two(unsigned x) returning 1 if x is a power of two (1, 2, 4, 8, ...) and 0 otherwise. 0 is not a power of two.

Starter code

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.