Leetcode(9)回文数

时光总嘲笑我的痴心妄想 提交于 2019-12-01 10:27:06

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    ##第二个条件是由于可能是奇回文数
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!