https://leetcode-cn.com/problems/palindrome-number
有一个星期没做题了,拿个简单的练下手。
看到题目第一个想法就是reversed([]):
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
list_x = list(str(x))
if list_x == list(reversed(list_x)):
return True
else:
return False
执行用时:556 ms,非常慢!
那就不用额外空间,只比较一半的数:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 or (x % 10 == 0 and x !=0):
return False
half_num = 0
while x > half_num: # x有len(str(x))//2的长度
half_num = half_num * 10 + x % 10
x = x // 10
return x == half_num or x == half_num // 10
执行用时: 644 ms,更慢了,可能是因为有乘法计算。
看了下更简单的Python解法:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return str(x) == str(x)[::-1]
额~Python大法好!