TL;DR
Reverse only half the digits arithmetically and compare to the other half β O(logββ x) time, O(1) space.
Approach 1 β Brute force (string conversion)
The direct reading: turn the number into a string and check it against its reverse.
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
return s == s[::-1]
Complexity: O(d) time where d is the number of digits, O(d) space for the string. Correct and simple β but it uses extra space, and the problem specifically invites an integer-only method.
Approach 2 β Reverse the whole number arithmetically
The insight: rebuild the number with its digits reversed using only arithmetic, then compare. Peel digits off the right with % 10 and push them onto a growing rev with rev = rev * 10 + digit.
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
original = x
rev = 0
while x > 0:
x, digit = divmod(x, 10)
rev = rev * 10 + digit
return rev == original
Complexity: O(d) time, O(1) space (in languages with fixed-width ints the full reversal can overflow; Pythonβs big integers make this safe, but reversing only half avoids the issue entirely).
Approach 3 β Reverse only the second half (in-place, no overflow)
The insight: you never need the whole reversal. Build rev from the trailing digits while shrinking x from the front; once x <= rev, you have consumed half the digits. Then a palindrome satisfies x == rev (even length) or x == rev // 10 (odd length β the middle digit sits alone in rev and is discarded).
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
Walkthrough with x = 12321:
| step | x | rev |
|---|
| start | 12321 | 0 |
| 1 | 1232 | 1 |
| 2 | 123 | 12 |
| 3 | 12 | 123 |
Now x = 12 is not greater than rev = 123, so the loop stops. The middle digit 3 lives in rev; drop it with rev // 10 = 12, which equals x β True.
For x = 1221: the loop runs to x = 12, rev = 12; x == rev β True.
Complexity: O(d) time (half the digits), O(1) space, and β importantly β rev only ever holds half the digits, so it cannot overflow a fixed-width integer.
Common pitfalls
- Forgetting that negatives are never palindromes.
- Missing the trailing-zero case: numbers like
10, 100 end in 0 but canβt start with 0, so theyβre not palindromes (except 0 itself).
- In the half-reversal, mishandling odd-length numbers β you must compare
x against rev // 10, not just rev.
Pattern takeaway
Digit-manipulation problems rarely need string conversion: % 10 peels the last digit and // 10 drops it, while rev * 10 + digit grows a reversed value. When you only need to compare halves, reverse just half the digits β it halves the work and sidesteps integer overflow.