File: power-of-four/solution.py

Date: 2026-06-06

Time: 18:33

power-of-four/solution.py

Purpose

This file solves LeetCode 342 — Power of Four. It determines whether a given integer is an exact power of four (1, 4, 16, 64, 256, ...) using a single-expression bit manipulation approach — no loops, no logarithms, no recursion.

Key Components

isPowerOfFour(n: int) -> bool — The sole function. It combines three conditions with short-circuit and:

1. n > 0 — Powers of four are strictly positive. Eliminates 0 and all negatives immediately.

2. n & (n - 1) == 0 — The classic power-of-two test. A power of two has exactly one set bit; n - 1 flips that bit and sets all lower bits, so the AND zeroes out. This eliminates numbers like 6, 12, 24 that have multiple set bits.

3. n & 0x55555555 != 0 — Distinguishes powers of four from other powers of two. 0x55555555 is 0101 0101 ... 0101 in binary — it has bits set at positions 0, 2, 4, 6, 8, ... (the even positions). Powers of four (4^k = 2^(2k)) always have their single set bit at an even position. Powers of two that aren't powers of four (like 2, 8, 32) have their set bit at an odd position and fail this check.

Patterns

Bit-mask filtering — Rather than computing log4(n) or looping with division, this uses a constant bitmask to distinguish powers of four from powers of two in O(1) time and space. This is idiomatic for LeetCode "power-of-X" problems.

Short-circuit conjunction — The three checks are ordered cheaply: the sign check is trivially fast and eliminates half the integer domain; the power-of-two check eliminates almost everything else; the mask check is the final discriminator.

Dependencies

Imports: None. Pure arithmetic on a single integer.

Imported by: power-of-four/test_solution.py directly. The "Imported By" list in the prompt is misleading — those are test files for *other* problems that share a common test runner, not files that call isPowerOfFour.

Flow

Straight-line: evaluate three boolean sub-expressions left to right with short-circuit and. No branching, no state, no mutation. Returns True or False.

Invariants

Error Handling

None. The function handles every integer gracefully — negatives and zero return False via the first check. No exceptions are raised or caught.

Beliefs