回文数Python解法

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
 

例:

输入:x = 121
输出:true

输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

# 1 双指针。两个指针指向中心,然后像两端遍历。

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        s = str(x)
        length = len(s)
        left, right = 0, 0
        if length & 1 == 1:
            left, right = int(length//2), int(length//2)
        else:
            left, right = int(length/2-1), int(length/2)
        while left >= 0 and right < length:
            if left == 0 and right == length - 1:
                if s[left] == s[right]:
                    return True
            if s[left] != s[right]:
                return False
            left -= 1
            right += 1

# 2 直接Python正反遍历即可:若正反遍历相同则代表是回文数

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        return x>-1 and str(x)[::-1]==str(x)

# 3 在不将整数转换成字符串的情况下解决。使用除余。

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        yu, y, x2 = 0, 0, x  # 余数,翻转后的结果,当前x
        while x2 != 0:
            yu = x2%10  # 求余
            y = y*10 + yu  # 计算翻转
           x2 = x2//10  # x右移一位
        
        return y==x

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值