当前位置 博文首页 > 明圣的博客:9. 回文数(简单)

    明圣的博客:9. 回文数(简单)

    作者:[db:作者] 时间:2021-08-07 15:40

    第一种方法:用整数转字符串的方式

    class Solution:
    def isPalindrome(self, x: int) -> bool:
    #特殊情况,如果是负数 or 0
    if x < 0 :
    return False
    if x == 0 :
    return True
    #普通情况
    if x > 0 :
    chx1 = ‘%d’%x #整数转换为字符串
    x1 = list(chx1) #转换成列表
    x1.reverse() #反转列表
    chx2 = ("".join(x1)) #列表转字符串
    if chx2 in chx1 :
    return True
    else :
    return False

    笔记:1、True和Flase首字母一定要大写
    2、整数转换成字符串, x = 123, chx1 = ‘%d’%x
    3、列表转字符串,chx2 = ("".join(x1))

    第二种:用数学公式的方式

    class Solution:
    def isPalindrome(self, x: int) -> bool:
    #特殊情况,如果是负数 or 尾数为0(不止一位数)
    if x < 0 :
    return False
    if (x % 10 == 0) and (x != 0):
    return False
    #普通情况
    y = 0
    #x末尾为0是回文数,下面式子同样满足
    #只需要对比一半,这样不用担心数字反转后的溢出问题
    while x > y :
    y = y*10 + x % 10
    x = x // 10
    return y == x or y//10 == x

    笔记:1、python3中,y/10并不能达到y//10的效果,仍然有小数

    cs