Palindrome Number
题目:
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.
不能使用额外空间,不能翻转因为可能溢出,说的我好怕怕>_<
多说无益,实践是检验真理的唯一方式,好的,让我们开始解题吧
直接讲头和尾进行比较,每次在头尾减少一位,就OK了,比较简单
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)return false;
int max = 1;
while(x/10/max>=1){
max*=10;
}
bool flag = true;
for(int i=10;max>=i;max/=100){
if(x%i==x/max){
x= (x-(x/max*max+x%i))/10;
}else{
flag = false;
break;
}
}
return flag;
}
};