Editor

Power of Two

#31 · Bit manipulation · Beginner · 30 XP · about 4 min

The powers of two are 1, 2, 4, 8, 16, 32 and so on: each one is double the one before.

Write is_power_of_two(n) that returns True if the integer n is a power of two and False otherwise. Zero and negative numbers are never powers of two.

Examples

is_power_of_two(16)    # returns True
is_power_of_two(1)     # returns True    (2 to the power 0)
is_power_of_two(12)    # returns False

Note

In binary, a power of two is a single 1 followed by zeros: 16 is 10000. Can you answer without a loop?

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.