Level 1 Power of Two
The Bit Check guards the gate of the Binary Keep: it opens only for powers of two (1, 2, 4, 8, …, 2^k for k >= 0). Zero and negatives never get in.
Write is_power_of_two(n: int) -> bool.
is_power_of_two(64) # True (1000000 in binary)
is_power_of_two(72) # False (1001000)
is_power_of_two(1) # True (2^0)
is_power_of_two(0) # False
is_power_of_two(-8) # False
-2^31 <= n <= 2^31 - 1. Dividing by two in a loop works, but there's a one-line answer with no loop.
⭐ Bonus: a speed test with 300,000 checks earns a star at O(1) per check.
Show hint
in binary, a power of two has exactly one 1. Write n - 1 under it and compare the two rows.