题目如下:
Determine whether an integer is a palindrome. Do this without extra space.
解题解题思路:
该问题最大的难道在于无额外的空间,如果没有此限制,可以将数字转换成String然后对String反转比较两个字符串是否相等就可以了,但是,既然有了此限制,就得去想其他方法了。先借用一个中间变量判断该数字的长度,然后根据数的长度和回文数字的性质进行操作;注意负数不是回文数。
提交的代码如下:
public boolean isPalindrome(int x) {
if(x < 0 || x > 2147483647) return false;
if(x < 10) return true;
int i= 0;
int tmp = x;
while(tmp > 0){
tmp /= 10;
i++;
}
while(i> 0){
i--;
if((x % 10) != (int)(x / Math.pow(10, i))){
return false;
}
x = (int)(x % Math.pow(10, i) - x % 10) / 10;
i--;
}
return true;
}