[Leetcode][python]Reverse Integer/反转整数

题目大意

反转整数123变为321,-123变为-321

注意:在32位整数范围内,并且001要成为1

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

解题思路

该题最主要的是,判断越界问题

https://leetcode-cn.com/problems/reverse-integer/solution/

要在没有辅助堆栈 / 数组的帮助下 “弹出” 和 “推入” 数字,我们可以使用数学方法。

//pop operation:
pop = x % 10;
x /= 10;

//push operation:
temp = rev * 10 + pop;
rev = temp;

但是,这种方法很危险,因为当 temp=rev10+pop temp = rev ⋅ 10 + pop 时会导致溢出。

幸运的是,事先检查这个语句是否会导致溢出很容易。

这里写图片描述

因为:2^31 -1= 2147483647 -2^31 = -2147483648

代码

Java

class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}

Python

python没有溢出问题,处理这题投机取巧

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x < 0:
            result = -int(str(-x)[::-1])  # 字符串倒序输出
        else:
            result = int(str(x)[::-1])
        if result < -2147483648 or result > 2147483647:
            return 0
        return result

总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值