File: palindrome-number/solution.py

Date: 2026-06-06

Time: 18:27

Palindrome Number — palindrome-number/solution.py

Purpose

This file implements LeetCode problem #9 (Palindrome Number). It determines whether an integer reads the same forwards and backwards, using a math-only approach — no string conversion. It's one of the foundational solutions in this repo, and based on the importedby list, its test file is imported by hundreds of other test modules (likely via a shared test infrastructure pattern, not because those modules use ispalindrome directly).

Key Components

is_palindrome(x: int) -> bool — The sole public function. Contract: given any integer, returns True if it's a palindrome, False otherwise.

Patterns

Half-reversal technique. Rather than reversing the entire number and comparing (which risks integer overflow in languages with fixed-width integers), this reverses only the second half of the digits and compares it to the first half. The loop while x > reversed_half naturally stops at the midpoint — when the remaining digits (x) are fewer than or equal to the reversed digits.

This is the canonical O(log₁₀ n) time, O(1) space solution for this problem.

Dependencies

Imports: None — pure function with no dependencies.

Imported by: palindrome-number/testsolution.py directly. The massive importedby list in the prompt reflects the test infrastructure — those test files likely import a shared helper or conftest that references this module indirectly, not is_palindrome itself.

Flow

1. Early rejection (line 12): Negative numbers are never palindromes. Numbers ending in 0 (except 0 itself) can't be palindromes because no number starts with 0.

2. Half-reversal loop (lines 14–16): Peel digits off the right side of x and build reversedhalf from them. Each iteration, reversedhalf grows by one digit (multiply by 10, add the last digit of x) while x shrinks by one digit (integer divide by 10). The loop exits when x <= reversed_half, meaning we've reached or passed the midpoint.

3. Midpoint comparison (line 18): Two cases:

Invariants

Error Handling

None needed. The function is total — it handles every integer input and always returns a bool. No exceptions are raised or caught.

Topics to Explore

Beliefs