9. Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Solution
(1) Java
Pay attention that integer may be a big number, so you have to consider overflow, then when compare most left digit and most right digit, consider zero, so you should keep left unchanged, but just move to the rigth, the most right uses module to shift left:
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int max = 1;
int y = x;
while (y/max >= 10) {
max *= 10;
}
while (x > 9 && max > 0) {
if ((x/max)%10 != x%10) {
return false;
}
x = x / 10;
max = max/100;
}
return true;
}
But this question should be ok using integer reverse, because if reversed integer overflow, thic means this is not palindrome.
(2) Python
Reverse integer directly, not need to consider overflow
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
rst = 0
y = x
while y > 0:
rst = rst*10 + y%10
y = y/10
return rst == x
(3) Scala
Here x/expo must be > 9 otherwise, expo can be overflow
def isPalindrome(x: Int): Boolean = {
if (x < 0) {
return false
}
var expo = 1
while (x/expo > 9) {
expo = expo*10
}
var y = x
while (y > 0 && expo > 0) {
val left = (y/expo)%10
val right = y%10
if (left != right) {
return false
}
expo = expo/100
y = y/10
}
return true
}