Palindrome Number
Easy Digit reversal
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Decide whether an integer reads the same forwards and backwards, without converting it to a string.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: do the digits read the same from both ends, without turning the number into a string?
Why this works: build the reverse of the second half digit by digit. When the reversed half catches up with the front half, compare them. Half is enough, and it can't overflow.
Example: x = 1221
x=1221, rev=0 → rev=1, x=122x=122, rev=1 → rev=12, x=12x == rev (12 == 12) → palindrome
✦Hints open one at a time
↗Approach
Reject negatives and numbers ending in 0 (except 0 itself). Move digits from x into rev until rev >= x. For even length x == rev, for odd length x == rev / 10 (the middle digit doesn't matter). Reversing only half also avoids overflow.
</>Solution (Java)
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int rev = 0;
while (x > rev) {
rev = rev * 10 + x % 10; // move last digit of x to rev
x /= 10;
}
return x == rev || x == rev / 10; // odd length: drop the middle digit
}
}
!Common mistake
Reversing the whole number into an int, which can overflow for large inputs.
- Time: O(log10 n) — one step per digit.
- Space: O(1).
