https://leetcode.com/problems/palindrome-number/
9. Palindrome Number
- Total Accepted: 156158
- Total Submissions: 467127
- Difficulty: Easy
- Contributors: Admin
Determine whether an integer is a palindrome. Do this without extra space.
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.
Code
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0 or (x > 0 and x % 10 == 0): return False sum = 0 while x > sum: sum = sum * 10 + x % 10 x = x / 10 return x == sum or x == (sum/10)
Idea
Create a variable, sum
, that sums the digits reading from the right to left. Note that the while loop stops when x<=sum
. Therefore, sum
will never be larger than original x
. This guarantees that `sum` will never cause overflow issue.
The final return condition is x==sum or x==(sum/10)
. However, any number that is multiples of 10 also satisfies this condition. That is why we need to exclude multiples of 10 in line 7-8.
Reference: