Determine whether an integer is a palindrome. Do this without extra space.
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.
Solution:
Because we cannot use the extra space, so we can try the math method: refer to the 007. reverse Integer.
calculate the first digit and the last digit of the integer, compare them,
if first == last, then discount them from the original number, (the result must divide 10 here)
must consider each special cases here!
下面的代码尚未来得及pass OJ,先行记录下来,LeetCode 服务器挂掉了~
以下代码已pass OJ, 需要注意对count的处理,保证首尾数字每次各向内缩进1位, count / 100
public class Solution {
public boolean isPalindrome(int x) {
// Start typing your Java solution below
// DO NOT write main() function
if(x<0){
return false;
}
int first = 0;
int last = 0;
int temp = x;
int count = 1;
while(temp >= 10){
temp = temp/10;
count *= 10;
}
while(x>=0){
if(x<10){
return true;
}else if(x==10){
return false;
}
last = x % 10;
first = x / count;
if(first == last){
x = (x - first*count - last) / 10;
count = count / 100;
//must deal with the count! 10022001
}else{
return false;
}
}
return false;
}
}
2015-04-06 update: python solution
数学解法,首先比较数字左右两端,然后去掉头尾数字继续比较。
class Solution:
# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False
len = 0
temp = x
while temp > 0:
len += 1
temp /= 10
while x >= 0 and len > 0:
left = x / (pow(10, len-1))
right = x % 10
if left != right:
return False
x = (x - left * pow(10, len-1))/10
len -= 2
if 0 <= x < 10:
return True