Leetcode刷题笔记之 Palindrome Number(python实现)

Leetcode刷题笔记之 Palindrome Number(python实现)

题目描述

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

  • Example 1:
    Input: 121
    Output: true
  • Example 2:
    Input: -121
    Output: false
    Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
  • Example 3:
    Input: 10
    Output: false
    Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

题目翻译

确定整数是否是回文。当一个整数向后读取与向前读取相同的内容时,它就是一个回文。

思路方法

  • 负数都不是回文数
  • 不能通过将数字转为字符串来判断回文,因为使用了额外的空间(即只能使用空间复杂度 O(1) 的方法)
  • 注意整数溢出问题

代码实现

  • 思路一
    因为 Python 语言本身的特性,这里反转整数时不需要考虑溢出,但不代表如果是C/C++等语言也不需要考虑。
    另外,特定于本问题,溢出与否对结果没有影响。因为原数字是正常无溢出的,那么如果反转溢出则说明反转后的数字与原数字不相等。
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:# 输入数值为负数
            return False

        tmp = x # 将输入数值赋值给临时变量
        # 将原数字进行反转
        y = 0  
        while tmp:
            y = y*10 + tmp%10
            tmp = tmp/10
        return y == x
  • 思路二:
    对思路一进行优化,将原数字反转一半就可以判断是否是回文。另外,以0结尾的非零数都不是回文。
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
         if x < 0 or (x != 0 and x%10 == 0):# 以0结尾或者负数不是回文
            return False
        
        #将原数字进行反转一半
        y = 0
        while x > y:
            y = y*10 + x%10
            x = x/10
        return x == y or y/10 == x

总结

  • 对于一个整数反转,需要考虑溢出问题,其数值范围是 [−2^31,2 ^31 − 1]。
  • 需要掌握给定一个整数如何分离各个数字:
    方法一:数字除10求出余数 ,那个余数就是个位数,然后求商代表没有个位数的数,然后重复做重复性操作。
    方法二:将正整数转化成字符串,再进行提取各个字符。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值