File: confusing-number/solution.py

Date: 2026-06-06

Time: 15:48

Confusing Number — Solution Explanation

Purpose

This file implements LeetCode 1056 - Confusing Number. It determines whether a number, when rotated 180 degrees, produces a different valid number. For example, 6 rotated becomes 9, and 69 rotated becomes 69 — but since 69 equals itself, it's *not* confusing. Meanwhile, 9 becomes 6, which *is* different, so 9 is confusing.

Key Components

Solution.confusingNumber(self, n: int) -> bool

The sole method. Contract: given a non-negative integer n, return True if rotating it 180 degrees yields a different valid number.

rotate dict — Maps each digit to its 180-degree rotation. Only five digits survive rotation:

Digits 2, 3, 4, 5, 7 have no valid rotated form.

Flow

1. Save the original value of n.

2. Extract digits from n right-to-left via % 10 / //= 10.

3. For each digit, check membership in rotate. If absent, short-circuit False — the number contains an unrotatable digit.

4. Build the rotated number left-to-right: rotated = rotated * 10 + rotate[digit]. Because digits are extracted least-significant-first but prepended most-significant-first, this naturally reverses the digit order — which is exactly what 180-degree rotation does (flip each digit *and* reverse their order).

5. Compare rotated != original. A confusing number must differ from itself after rotation.

Patterns

Digit-by-digit extraction with simultaneous reconstruction — a common idiom for "reverse a number" problems. Here it does double duty: reversing digit order *and* mapping each digit through the rotation table in a single pass.

Lookup table for validity + transformation — the rotate dict serves as both a whitelist (membership test) and a mapping function. This avoids separate validation and transformation steps.

Dependencies

Invariants

Error Handling

None. The method assumes valid input per LeetCode conventions. No exceptions are raised; invalid digits cause an early False return, not an error.

Topics to Explore

Beliefs