python算法日记 _leetcode 9. 回文数

9. 回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121
输出: true
示例 2:

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

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:

你能不将整数转为字符串来解决这个问题吗?

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

非进阶,用字符串

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

非进阶,用字符串+指针

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

进阶,利用数字可加减乘除的特性,反转数字的后一半,跟前一半做比较,参考leetcode官方的c#代码
链接:https://leetcode-cn.com/problems/palindrome-number/solution/hui-wen-shu-by-leetcode/
来源:力扣(LeetCode)
 

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0 or (x!=0 and x%10==0):
            return False
        re_half = 0
        while x>re_half:  #停止条件很巧妙
            re_half = re_half*10+x%10  #将后半段数组反转
            x = x//10
        return re_half==x or re_half//10==x #or前面判断偶数个数字 or后面判断奇数个数字
发布了43 篇原创文章 · 获赞 0 · 访问量 1885

猜你喜欢

转载自blog.csdn.net/weixin_39331401/article/details/104747896