Problem 9. Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
My solution in Python:
Determine whether an integer is a palindrome. Do this without extra space.
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False copy, reverse = x, 0 while copy: reverse *= 10 reverse += copy % 10 copy /= 10 return x == reverse
Review:
After much thought, I cannot solve the problem without using extra space, so my solution does use some extra space as a new integer is constructed.
Negative numbers cannot be palindromic due to the preceding “-” sign which doesn’t exist at the end, so we first check whether the given number is less than 0.
If it is greater than or equals 0, we construct a reversed version of this integer, then compare them. If the original integer equals to its reversed version, then the number is palindromic.