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.
思路:
将数字的最高位和最低位进行异或,异或的结果加在一起,如果大于零则返回false,否则为true。注意负数都为false。
1 bool isPalindrome(int x) { 2 // Start typing your C/C++ solution below 3 // DO NOT write int main() function 4 if(x < 0) 5 return false; 6 if(x > -1 && x < 10) 7 return true; 8 int l = 0; 9 int i; 10 int t = x; 11 while(t != 0){ 12 l++; 13 t /= 10; 14 } 15 t = 0; 16 while(t == 0 && l>1){ 17 t += (int)(x/pow(10,l-1))^(x%10); 18 x %= (int)pow(10,l-1); 19 x /= 10; 20 l -= 2; 21 } 22 if(t == 0) 23 return true; 24 return false; 25 }