1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第九题
(1)题目
英文:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
中文:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
(2)解法
① 使用str(耗时: 72ms,内存:13.6M)
class Solution:
def isPalindrome(self, x: int) -> bool:
if x >0 and int(str(x)[::-1]) == x:
return True
elif x < 0 or int(str(x)[::-1]) != x:
return False
else:
return True
# 或者直接用一句话
return str(x) == str(x)[::-1] # (耗时: 104ms,内存:13.8M)
注意:
1.else中的情况是:x=0或者x < 0 and int(str(x)[::-1]) != x,由于是顺序执行的,所以在elif中就已经将x < 0 and int(str(x)[::-1]) != x的情况给输出为False了,else中只输出x=0为True的情况了
② 直接计算出翻转后的数字(耗时: 88ms,内存:13.7M)
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
if len(str(x)) >=2:
shang, yushu = divmod(x, 10)
if int(str(yushu) + str(shang)[::-1]) == x:
return True
else:
return False
else:
return True
注意:
1.这种使用除10的方法只能适用于x的位数大于等于2的情况,如果是一位数,则直接判断是True的了。