简繁EN

LeetCodeNo. 096

【LeetCode with Python】 9. Palindrome Number

目錄

題目

原題頁面:https://leetcode.com/problems/palindrome-number/
題目型別:Math
難度評價:Easy
類似題目:(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.


分析

判斷一個數值是否是迴文。首先負數肯定不是迴文,而0~9則是迴文。基本的思路是每次對比數值開頭的數字和結尾的數字,看是不是相等。結尾的數字可以通過對10取餘得到,於是問題的關鍵就在於怎樣取出開頭的數字了。
注意不要去嘗試將整個數值倒置,這樣可能會造成溢位。(不過如果這個數值是迴文的話,倒置也不會溢位就是了。但是有沒有可能一個數值本來不是迴文,倒置後溢位的結果反而等於原數值了???)


程式碼

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

本文地址:https://xnerv.wang/zh-tw/leetcode-palindrome-number/