leetcode python3 回文数

xiaoxiao2025-11-03  6

一、整个数翻转判断

1.思路:负数的回文肯定为false,0肯定为true,正数通过对10求余数和求除数运算将数翻转,最后判断与原先的值是否相等

2.代码

class Solution: def isPalindrome(self, x): if x<0: return False elif x==0: return True elif x>0: x1=x tmp=0 while x!=0: tmp=tmp*10+x%10 x=int(x/10) if tmp==x1: return True else: return False

二、一半数目翻转判断(更快更好)

class Solution: def isPalindrome(self, x): if x==0: return True elif x<0 or x%10==0: return False else: tmp=0 while x>tmp: tmp=tmp*10+x%10 x=int(x/10) if tmp==x or x==int(tmp/10): return True else: return False

 

转载请注明原文地址: https://www.6miu.com/read-5038988.html

最新回复(0)