Python3_Leetcode #9 回文数题解
2021/7/9 1:06:37
本文主要是介绍Python3_Leetcode #9 回文数题解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
思路:
1. 数字倒序比较法(基于LeetCode#8 数字反转来完成)
a. 将输入数字通过%10 求余 取反转
b.反转后数字与原来输入比较,一致则返回true
python3:
def isPalindrome(self, x: int) -> bool:if x < 0 : #一开始加了x%10 == 0 这个判断,但是这样如果输入0 则会是错误的。所以去除 return False reverse = 0 original = x
while x>0 : x,pop = divmod(x,10) reverse = reverse*10 + pop if reverse == original : return True else: return False 2. 字符串反转比较 思路和1类似,只不过通过字符串来进行反转。 def isPalindrome(self, x: int) -> bool:
if x < 0 : return False elif x == 0: return True else: y = int(str(x)[::-1]) if x == y: return True else: return False ----------------------------------------------
class Solution:
def isPalindrome(self, x: int) -> bool:return str(x)==str(x)[::-1]
这篇关于Python3_Leetcode #9 回文数题解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python