Leetcode(9)回文数
[题目表述]:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
第一次:直接全部转
执行用时:148 ms; 内存消耗:13.4MB 效果:还行
class Solution: def isPalindrome(self, x: int) -> bool: s=str(x) if s==s[::-1]: return True else: return False
第二种方法:反转一半数字
执行用时:156 ms; 内存消耗:13.2MB 效果:还行
原因:1.额外空间 2.反转整数溢出
算法:1.负数全不是 2.反转后一半:利用%10/10 3.判断到一半:反转数字>未反转数字
class Solution: def isPalindrome(self, x): rev = 0 if not x: return True if x<0 or not x % 10: return False else: while x > rev: rev = rev * 10 + x % 10 x //= 10 return x == rev or x == rev // 10 ##第二个条件是由于可能是奇回文数