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.
JAVA
注意:零和负数没有回文!
这个题有两种做法,一种是先写出其反向数,然后判断一下它是不是和原
数相等,这在之前做过reverse integer可以让你好做很多。
另一种做法需要你先除10遍历一遍,记住整数的位数(或者数量级)。第二遍然后左端用先除法再求余依次得到高位、右端用先求余再除法依次得到低位,判断是否相等。
解法一:
public class Solution {
public boolean isPalindrome(int x) {
if(x<0||x==Integer.MIN_VALUE)
{
return false;
}
int num = Math.abs(x);
int res = 0;
while(num!=0)
{
if(res>(Integer.MAX_VALUE-num%10)/10)
return false;
res = res*10+num%10;
num /= 10;
}
res=x>0?res:-res;
if(res==x)
{
return true;
}else{
return false;
}
}
}
解法二:
public class Solution {
public boolean isPalindrome(int x) {
if(x<0)
return false;
if(x<10)
return true;
int len = 1;
int n =0;
int a = x;
//这里起初用的是a!=0来作为循环结束的
//但会多出的一次len*10,而这最后一次会导致溢出,即使再/10也晚了。
while(a>9)
{
a = a/10;
len *= 10;
n++;
}
n++;
n /= 2;
a = x;
int b = x;
for(int i=0;i<n;i++)
{
if( ((a/len)%10) != (b%10) )
return false;
len /= 10;
b /= 10;
}
return true;
}
}
不过查了一下发现第二种方法有最简单的写法:
bool isPalindrome(int x) {
if (x<0) { return false; }
int len=1;
for (len=1; (x/len) >= 10; len*=10 );
while (x != 0 ) {
int left = x / len;
int right = x % 10;
if(left!=right){
return false;
}
x = (x%len) / 10;
//len为输入数字x的数量级,此处作用为将原数字掐头(%10)去尾(/10)
len /= 100;
//掐头去尾之后减少了两位所以原数数量级也减小了10的2次方倍
}
return true;
}