Determine whether an integer is a palindrome. Do this without extra space.
判断一个整数是否为回文。首先负数不是回文,然后题目要求不能有额外的空间,因此不能用栈的办法,也不能保存每个位数的数字,只能通过扫描整数位置,并进行前后判断。
如下所示:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0){
return false;
}
int y = x, z = x;
long indexRight = 1;
while (y != 0){
indexRight = indexRight*10;
y = y/10;
}
int highVal = 0, lowVal = 0, indexLeft = 1;
while (indexRight != 1&&indexRight >= indexLeft){
highVal = (int)(z/(indexRight/10))%10;
lowVal = (int)(z/indexLeft)%10;
if (highVal != lowVal){
return false;
}
indexRight = indexRight/10;
indexLeft *= 10;
}
return true;
}
}