File: power-of-two/solution.py

Date: 2026-06-06

Time: 18:34

power-of-two/solution.py

Purpose

This file solves LeetCode #231 — Power of Two. It provides a single function ispowerof_two that determines whether a given integer is an exact power of two (1, 2, 4, 8, 16, ...). It's one of ~500 solutions in the repo, following the standard one-file-per-problem layout.

Key Components

ispowerof_two(n: int) -> bool — The sole function. Takes an integer and returns whether it's a power of two.

Patterns

The implementation uses the classic bit-manipulation trick: n & (n - 1) == 0.

Why this works: a power of two in binary has exactly one bit set (e.g., 8 = 1000). Subtracting 1 flips that bit and sets all lower bits (7 = 0111). ANDing the two produces zero — and this *only* happens when there's exactly one set bit.

The n > 0 guard is essential because n = 0 would pass the bit test (0 & -1 is 0), and negative numbers are never powers of two.

This is O(1) time and space — no loops, no division, just two arithmetic operations and a comparison.

Dependencies

Imports: None. Pure standalone function with no external dependencies.

Imported by: The "Imported By" list in the prompt is misleading — those ~500 test files don't import *this* solution. They import their *own* solution.py files. The actual consumer is power-of-two/test_solution.py.

This function is also a building block for the related problems power-of-four and power-of-three in the repo, which use different techniques but share the same structural pattern.

Flow

1. Check n > 0 — reject zero and negatives immediately (short-circuit).

2. Compute n & (n - 1) — clear the lowest set bit.

3. Return whether the result is zero (meaning n had exactly one set bit).

Invariants

Error Handling

None. The function is total — it handles all integer inputs by returning False for anything that isn't a positive power of two. No exceptions raised.

Topics to Explore

Beliefs