Palindrome Number
Given an integer `x`, return `true` if `x` is a palindrome, and `false` otherwise. **Core Insight:** A negative number is never a palindrome. A number ending in 0 (except 0 itself) is never a palindrome. The cleanest approach reverses only the second half of the number and compares it to the first half — this avoids overflow from reversing the entire number. **Algorithm:** Handle edge cases first (negative, or ends in 0 but isn't 0). Then reverse digits one by one into `reversed` while `x > reversed`. When the loop ends, `x` holds the first half and `reversed` holds the reversed second half. For even-length numbers check `x == reversed`; for odd-length check `x == reversed / 10` (the middle digit doesn't matter). **Why avoid string conversion:** The problem asks for a solution without converting to a string — the half-reversal trick achieves this cleanly. **Complexity:** Time O(log₁₀ n) — we process half the digits. Space O(1).
Constraints
- •
-2³¹ ≤ x ≤ 2³¹ - 1
def isPalindrome(x: int) -> bool:
if x < 0 or (x % 10 == 0 and x != 0):
return False
rev = 0
while x > rev:
rev = rev * 10 + x % 10
x //= 10
return x == rev or x == rev // 10