NeetCode #909LC-9EasyMath & Geometry
← Back to All Problems#909 · #9 · Palindrome Number(回文数)
📌 Problem Statement & Constraints
Given an integer
x, return true if x reads the same forwards and backwards, otherwise false. Constraints: -2^31 <= x <= 2^31 - 1. The follow-up asks whether the problem can be solved without converting x to a string.💡 Core Algorithmic Approaches
- Negative numbers, and positive numbers ending in
0other than0itself, can never be palindromes. - Reverse only the second half of the digits: build
revfrom the low-order digits while shrinkingxfrom the high end. - Stop when
x <= rev, which means the halfway point has been passed. - For an even-length number the two halves are equal (
x == rev); for an odd-length number the middle digit is stored inrev, so comparex == rev // 10.
💻 Benchmark Python3 Implementation
class Solution:
def isPalindrome(self, 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⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log x): only half of the digits are processed.
💾 Space Complexity
O(1).
⚠️ Interview Pitfalls & Follow-ups
- Reversing the entire number: this can overflow in fixed-width languages, and the follow-up discourages the string route; reversing only half avoids both.
- Forgetting the trailing-zero case:
10,100and similar end in0and are not palindromes, but the half-reversal would mishandle them without the early check. - Using only
x == rev: odd-length palindromes such as12321leave the middle digit inrev, sox == rev // 10is also needed. - Looping with
while x != 0: that reverses all digits instead of stopping at the midpoint.