Determine whether aninteger is a palindrome. Do this without extra space.
click to show spoilers.
Some hints:
Could negative integers be palindromes? (ie, -1)
负数一律不是回文数字!
If you are thinking of converting theintegertostring, note the restriction ofusing extra space.
把整数转为字符串要注意额外空间的使用。
You could also try reversing aninteger. 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.
初步通过的代码:
publicclassSolution {publicboolean isPalindrome(int x) {
if(x<0){
returnfalse;
}
int ori = x;
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
intsum = 0;
while(x!=0){
if(sum>max/10||sum<min/10){
returnfalse;
}
sum = sum*10+x%10;
x/=10;
}
if(sum == ori){
returntrue;
}else{
returnfalse;
}
}
}
优化的代码:不需要考虑溢出
publicclass Solution {
public boolean isPalindrome(int x) {
if(x==0){
returntrue;
}
if(x<0||x%10==0){
returnfalse;
}
int rightPart = 0;
while (x>rightPart){
rightPart = rightPart*10 +x%10;
x = x/10;
}
if(rightPart==x || rightPart/10 ==x){
returntrue;
}
returnfalse;
}
}