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)
Turn the number into a string and compare it to its reverse.
def isPalindrome(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 asks for an integer-only method.
Approach 2 — Reverse the whole number arithmetically
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.
def isPalindrome(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)
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. A palindrome then satisfies x == rev (even length) or x == rev // 10 (odd length, where the middle digit sits alone in rev and is discarded).
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
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. Because rev only ever holds half the digits, 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.