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?
题目很简单,判断一个int是否是回文数字,需要注意的几点:
1. 负数不为回文数字
2. 不能使用额外的空间,如果将该int转成string处理,会使用额外的空间
3.如果使用将该int反转,然后比较与原int是否相等这种判断方法,需要处理int溢出的问题,比如2147483647,反转过来就大于了Interger.MAXVALUE
我先采用第三种解法,代码如下:
public boolean isPalindrome(int x) {
if(x < 0 )
return false;
int org = x;
int rev = 0;
while( org > 0){
if(Integer.MAX_VALUE / 10 < rev)
return false;
rev = rev * 10 + org % 10;
org = org / 10;
}
return rev == x;
}
如果反转之后产生了越界,说明int的最高位数字与个位数字不相等,可直接断定不为回文数字