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