Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

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.

 

 1 class Solution {
 2 public:
 3     int reverse(int x){
 4         int sign=x>0?1:-1;
 5         x=abs(x);
 6         long long res=0;
 7         while(x)
 8         {
 9             res=res*10+x%10;
10             x=x/10;
11         }
12 
13         if(res*sign>2147483647||res*sign<-2147483648)return 0;
14         else
15             return res*sign;
16 
17     }
18 
19     bool isPalindrome(int x) {
20         int tmp=0;
21         if(x<0)
22             return false;
23         tmp=reverse(x);
24         if(x==tmp)
25             return true;
26         else
27             return false;
28     }
29 };

 

posted on 2015-05-09 07:38  黄瓜小肥皂  阅读(127)  评论(0编辑  收藏  举报