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.
题解:
easy题
Solution 1
1 class Solution { 2 public: 3 bool isPalindrome(int x) { 4 if (x < 0) 5 return false; 6 int base = 1; 7 int tmp = x; 8 while (tmp > 9) { 9 tmp /= 10; 10 base *= 10; 11 } 12 13 while (x) { 14 int head = x / base; 15 int tail = x % 10; 16 if (head != tail) 17 return false; 18 x = (x % base) / 10; 19 base /= 100; 20 } 21 22 return true; 23 } 24 };
Solution 2
1 class Solution { 2 public: 3 bool isPalindrome(int x) { 4 if (x < 0) 5 return false; 6 int base = 1; 7 while (x / base > 9) { 8 base *= 10; 9 } 10 11 while (x) { 12 int head = x / base; 13 int tail = x % 10; 14 if (head != tail) 15 return false; 16 x = (x % base) / 10; 17 base /= 100; 18 } 19 20 return true; 21 } 22 };