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

  1. Negative numbers, and positive numbers ending in 0 other than 0 itself, can never be palindromes.
  2. Reverse only the second half of the digits: build rev from the low-order digits while shrinking x from the high end.
  3. Stop when x <= rev, which means the halfway point has been passed.
  4. For an even-length number the two halves are equal (x == rev); for an odd-length number the middle digit is stored in rev, so compare x == 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, 100 and similar end in 0 and are not palindromes, but the half-reversal would mishandle them without the early check.
  • Using only x == rev: odd-length palindromes such as 12321 leave the middle digit in rev, so x == rev // 10 is also needed.
  • Looping with while x != 0: that reverses all digits instead of stopping at the midpoint.