9. Palindrome Number
描述:
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
我的思路:
最开始看到题目想到了Reverse Integer这道题目的解决思路,即用String类来实现,但是题目要求不能用额外的空间,故这个思路不可行。所以考虑直接将数字倒转看二者是否相等,但是题目中又提示直接倒转可能会出现溢出的问题,所以考虑将数字分成两部分,比较一个整数的前半部分和后半部分的倒置是否相等即可。
以整数26362为例说明算法思路:可以很直观的想到用这个数字来模除10来得到最后一位数字,用这个数字来除以10来去掉最后的数字。26362%10=2,即最后一位数字为“2”,26362/10=2636,2636%10=6,2636/10=263,此时后半部分的倒置为2*10+6=26,与前半部分数字相等。算法结束的条件:我们是在输入x的基础上不断除以10来去掉最后一位数字的,所以当当前的x值小于等于后半部分的数字时即可结束循环。此外,我们还需要考虑到特殊情况:负数不可能是回文数,以及10的整数倍也不是回文数。
我的解决:
class Solution {
public boolean isPalindrome(int x) {
if(x < 0 ){
return false;
}
if(x%10==0 && x!=0)
return false;
int rev = 0;
while( x > rev){
rev = rev * 10 + x%10;
x=x/10;
}
return (x==rev || (x==rev/10));
}
}