Approach 1Optimal▶ Animated
Reverse and compare
Negatives are not palindromes (the minus sign). Reverse the digits of a non-negative x and compare.
Reversing 121 yields 121. Reversing 10 yields 01 → 1. No string conversion required.
Algorithm
- If
x < 0, return false. - Build
revby popping digits offxintorev * 10 + digit. - Compare
revto the original.
- Time
- O(log x)
- Space
- O(1)
class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False orig, rev = x, 0 while x: rev = rev * 10 + x % 10 x //= 10 return rev == orig