Determine whether an integer is a palindrome. Do this without extra space.python
Notes: any negative number is not palindrome.git
Example 1:github
Input: 1221 Output: True
Example 2:this
Input: -1221 Output: False
不能使用額外的變量,只能用參數x完成,因爲不能使用額外變量的限制,因此代碼可讀性有點差spa
將int轉成str,利用len(str)求出整數的位數,而後用str字符串的切片來取得先後對稱部分,如input爲x = 1234
則len(str(x))
爲4,3
的下標爲len(str(x))//2
.net
利用python切片能夠快速reverse字符串, a = [1,2,3]
則a[::-1]
爲[3,2,1]
code
x = 1234
能夠經過判斷12
是否等於43
來得出是不是迴文,根據上一點12
能夠用切片str(x)[ : len(str(x))//2]
求得,43
能夠根據第4點用str(x)[len(str(x))//2 : ]
求得blog
仍然能夠分爲奇迴文和偶迴文處理,參考閱讀尋找字符串中最長迴文,12321
以3爲對稱中心,123321
以33爲對稱中心leetcode
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地址字符串