简繁EN

LeetCodeNo. 096

[LeetCode with Python] 9. Palindrome Number

Contents

Problem

Problem page: https://leetcode.com/problems/palindrome-number/
Topics: Math
Difficulty: Easy
Similar problems: (E) Palindrome Linked List

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.


Analysis

I need to check whether a number is a palindrome. A negative number can't be a palindrome, and the numbers 0~9 are all palindromes. The basic idea is to compare the first and last digits each time to see if they match. I can get the last digit by taking the number modulo 10, so the question is how to get the first digit.
Don't try to reverse the whole number, since that can cause overflow. (Though if the number is a palindrome, reversing it won't cause overflow anyway. But if the number isn't a palindrome, could reversing it cause overflow and leave me with the original number???)


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:

# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False
if x < 10:
return True
div = 1
val = x
while True:
val = int(val / 10)
if val > 0:
div *= 10
else:
break

while div > 0:
left = int(x / div)
right = int(x % 10)
if left != right:
return False
x = x % div
x = x / 10
div = int(div / 100)
return True

Article link: https://xnerv.wang/en/leetcode-palindrome-number/