~/problems / Bit manipulation

Power of Two

On a phone? Coding is easier on a laptop, and your draft saves in this browser. Meanwhile: quiz this topic or play this problem's boss fight .

easy ▶ boss game: The Bit Check 2 levels ~10 min

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.

Level 2 unlocks when level 1 passes.

Topic: Bit manipulation (IP / CIDR). IPv4 as a 32-bit int; lowest set bit for block sizes.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc