Palindrome Number
Problem
Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
x = 1221truedef is_palindrome(x):
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
function isPalindrome(x) {
if (x < 0 || (x % 10 === 0 && x !== 0)) return false;
let rev = 0;
while (x > rev) {
rev = rev * 10 + (x % 10);
x = Math.floor(x / 10);
}
return x === rev || x === Math.floor(rev / 10);
}
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;
x /= 10;
}
return x == rev || x == rev / 10;
}
}
bool isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int rev = 0;
while (x > rev) {
rev = rev * 10 + x % 10;
x /= 10;
}
return x == rev || x == rev / 10;
}
Explanation
A number is a palindrome if it reads the same forwards and backwards. Instead of turning it into a string, we cleverly build up the reverse of only the lower half of the digits and compare it with the upper half.
First, two quick rejects: any negative number is not a palindrome (the minus sign breaks symmetry), and any number ending in 0 (other than 0 itself) cannot be one, because its reverse would start with a leading zero.
Then we loop: each step pops the last digit of x with x % 10 and pushes it onto rev using rev = rev * 10 + x % 10, while shrinking x with x //= 10. We stop once x <= rev, meaning we have processed half the digits.
At the end the number is a palindrome if x == rev (even number of digits) or x == rev // 10 (odd number of digits, where the middle digit sits in rev and is dropped).
Example: x = 1221. We pop 1 then 2: rev becomes 12 and x becomes 12. Now x == rev, so it is a palindrome.