Leetcode 9 Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Click to show spoilers.
Some hints:
Cocould negative integers be palindromes? (Ie,-1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You cocould also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How wocould you handle such case?
There is a more generic way of solving this problem.
Very concise c ++ solution:
Only half of the replies
public boolean isPalindrome1(int x) { if (x == 0) return true; // in leetcode, negative numbers and numbers with ending zeros // are not palindrome if (x < 0 || x % 10 == 0) return false; // reverse half of the number // the exit condition is y >= x // so that overflow is avoided. int y = 0; while (y < x) { y = y * 10 + (x % 10); if (x == y) // to check numbers with odd digits return true; x /= 10; } return x == y; // to check numbers with even digits}
The python solution should be compared before and after:
class Solution: # @param x, an integer # @return a boolean def isPalindrome(self, x): if x < 0: return False ranger = 1 while x / ranger >= 10: ranger *= 10 while x: left = x / ranger right = x % 10 if left != right: return False x = (x % ranger) / 10 ranger /= 100 return True
Python string solution:
class Solution: # @param {integer} x # @return {boolean} def isPalindrome(self, x): return str(x)==str(x)[::-1]