栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

LeetCode之Python版本的“回文数”(简单题)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode之Python版本的“回文数”(简单题)

1.题目描述

2.算法思想
  • 转换为字符串,将字符串翻转,如果翻转前后字符串相等,则返回True,否则返回False。
  • 转换为字符串,循环字符串长度的一半,逐个判断字符串的首尾是否相等。若有一个不相等,则返回False,否则,返回True。
  • 对整数不断除以10,不断取余数,然后对余数不断乘以10,直到最初的整数为0。然后判断最初的数和最终通过余数生成的数是否相等,若相等,则返回True,若不相等,则返回False。
3.最终代码
  • 代码1
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        return str(x) == str(x)[::-1]
  • 代码2
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        x = str(x)
        length = len(x)
        for i in range(length//2):
            if x[i]!=x[length-i-1]:
                return False
        return True
  • 代码3
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        first_num = x
        res = 0
        while(x>0):
            res = res*10+x%10
            x =x//10
        if (res == first_num):
            return True
        else:
            return False
4.编写验证过程中的完整代码

只要给上述代码后面加上如下几行,即可输出验证。由于过于基础,此处就不再赘述,可以参考我本专栏其他较早博客的写法。

solution = Solution()
print(solution.isPalindrome(123456))
print(solution.isPalindrome(121))

拒绝内耗,永远心存善念。
不要恐惧,只管向前就好。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/934865.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号