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

Decide whether an unsigned integer is an exact power of two.

Task

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.

Input

A single unsigned x.

Output

Returns 1 if x is a power of two, otherwise 0.

Example

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

Edge cases

  • x == 0 returns 0 (no bits set).
  • 1 (= 2^0) is a power of two.

Rules

  • The x && !(x & (x-1)) trick checks for a single set bit without a loop.

Input format

A single unsigned x.

Output format

1 if x is a power of two, otherwise 0.

Constraints

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.