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.
Code:
public class Solution {
static int v;
public static boolean isPalindrome(int x) {
//optimizations
if(x<0) return false;
if(x<10) return true;
if(x%10==0) return false;
if(x<100&&x%11==0) return true;
if(x<1000&&((x/100)*10+x%10)%11==0) return true;
//actual logic
v=x%10;
x=x/10;
while(x-v>0)
{
v=v*10+x%10;
x/=10;
}
if(v>x){v/=10;}
return v==x?true:false;
}
}
中文解释:
比如 1234321;每次通过除以10和对10取余来保存下前半部分x和后半部分v,比如 x = 123432, v=1;
直到x=123,v=1234的时候,循环结束,再通过 v/10 == x,来判断数是不是回环的。
整数回文判断

本文介绍了一种不使用额外空间判断整数是否为回文数的方法,并提供了优化思路及核心代码实现。
697

被折叠的 条评论
为什么被折叠?



