Level 1 Power of Two
The Bit Check guards the gate of the Binary Keep. Every visitor is a number, and the gate opens only for powers of two: 1, 2, 4, 8, 16, … (2^k for some k >= 0). Zero and negative numbers never get in.
Write is_power_of_two(n: int) -> bool that says whether the gate opens for n.
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
Constraints:
-2^31 <= n <= 2^31 - 1.
Dividing by two in a loop works, but there's a one-line answer with no loop at all. Aim for O(1).
Show hint
in binary, a power of two has exactly one 1. Write out n - 1 under it and compare the two rows.