[Leetcode刷题] 第7题 Reverse Integer 整数反转

题目:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

解题思路:

假设我们正在处理一个只能存储32位有符号整数范围内的整数的环境:[−2^31,2^31 − 1]。 出于此问题的目的,假定您的函数在反向整数溢出时返回0。

"""
取x的符号的方法:
    1.sigh = [-1,1](x<0)
    2.x//abs(x)    不能计算0的情况
    3.int((x+0.1)//abs(x+0.1))    能计算0的情况
"""

具体代码:

class Solution:
    #方法一
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        sign = [1,-1][x < 0]
        rst = sign * int(str(abs(x))[::-1])
        return rst if -(2**31)-1 < rst < 2**31 else 0
    #方法二
    def reverse_better(self, x: int) -> int:
        y, res = abs(x), 0
        # 则其数值范围为 [−2^31,  2^31 − 1]
        boundry = (1 << 31) - 1 if x > 0 else 1 << 31
        while y != 0:
            res = res * 10 + y % 10
            if res > boundry:
                return 0
            y //= 10
        return res if x > 0 else -res


if __name__ == '__main__':
    o = Solution()
    a = 123
    b = o.reverse(x=a)
    print(b)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值