LeetCode题解(0009):判断整数是否为回文数(Python)
发布日期:2021-06-29 19:51:36 浏览次数:3 分类:技术文章

本文共 916 字,大约阅读时间需要 3 分钟。

LeetCode题解(0009):判断整数是否为回文数(Python)

(简单)

解法 执行用时 内存消耗
Ans 1 (Python) 164ms (>5.41%) 13.8MB (>5.88%)
Ans 2 (Python) 92ms (>50.10%) 13.6MB (>5.88%)
Ans 3 (Python) 84ms (>71.30%) 13.5MB (>5.88%)
Ans 4 (Python) 72ms (>94.21%) 13.6MB (>5.88%)

解法一(转换为列表反转比较):

def isPalindrome(self, x: int) -> bool:    l = [c for c in str(x)]    r = copy.deepcopy(l)    r.reverse()    return l == r

解法二(通过数值运算反转比较):

def isPalindrome(self, x: int) -> bool:    if x < 0:  # 处理负数的情况        return False    original = x  # 原始数值    ans = 0    while x > 0:        ans = ans * 10 + x % 10        x //= 10    return original == ans

解法三(转换为字符串逐个比较):

def isPalindrome(self, x: int) -> bool:    s = str(x)    a = 0    b = len(s) - 1    while a <= b:        if s[a] != s[b]:            return False        a += 1        b -= 1    return True

解法四(转换为字符串反转比较):

def isPalindrome(self, x: int) -> bool:    x = str(x)    y = x[::-1]    return x == y

参考文献:

转载地址:https://dataartist.blog.csdn.net/article/details/106751651 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(0013):将罗马数字转换为整数(Python)
下一篇:LeetCode题解(0007):整数前后反转(Python)

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年05月03日 02时12分38秒