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地址字符串