不使用任何額外變量判斷迴文數字
Palindrome Number
- Determine whether an integer is a palindrome. Do this without extra space.
Notes: any negative number is not palindrome.
Example 1:
Input: 1221
Output: True
- Example 2:
Input: -1221
Output: False
思路
- 不能使用額外的變量,只能用參數x完成,由於不能使用額外變量的限制,所以代碼可讀性有點差
- 將int轉成str,利用len(str)求出整數的位數,然後用str字符串的切片來取得前後對稱部分,如input爲
x = 1234
則len(str(x))
爲4,3
的下標爲len(str(x))//2
- 利用python切片可以快速reverse字符串,
a = [1,2,3]
則a[::-1]
爲[3,2,1]
x = 1234
可以通過判斷12
是否等於43
來得出是否是迴文,根據上一點12
可以用切片str(x)[ : len(str(x))//2]
求得,43
可以根據第4點用str(x)[len(str(x))//2 : ]
求得- 仍然可以分爲奇迴文和偶迴文處理,參考閱讀尋找字符串中最長迴文,
12321
以3爲對稱中心,123321
以33爲對稱中心
代碼
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if len(str(x)) % 2 == 0:
return int(str(x)[ : len(str(x))//2]) == int(str(x)[len(str(x))//2 : ][ : :-1])
else:
return int(str(x)[ : len(str(x))//2+1]) == int(str(x)[len(str(x))//2 : ][ : :-1])
本題以及其它leetcode題目代碼github地址: github地址