码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode(9)回文数

时间:2019-10-16 00:46:49      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:false   方法   etc   code   lse   数字   算法   执行   回文   

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    ##第二个条件是由于可能是奇回文数

Leetcode(9)回文数

标签:false   方法   etc   code   lse   数字   算法   执行   回文   

原文地址:https://www.cnblogs.com/ymjun/p/11681752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!