LeetCode Reverse Integer

本文介绍了一种用于反转整数的有效算法,并特别关注了处理32位整数时可能遇到的溢出问题。文章详细解释了如何避免整数反转过程中出现的溢出情况,并提供了一段实现该算法的Java代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

思路分析:这题比较简单,但是有一个tricky的地方,就是如何处理溢出的情况。首先要搞清楚,无论32位机器还是64位机器,java定义int为32位,所以Integer.MAX_VAULE和Integer_MIN_VALUE分别是2^31-1和-2^31,32位把第一位当成符号位,容易得出前面的计算结果(考虑进位的规律或者等比数列求和)。所以这题处理溢出有两个地方要注意,第一对于Integer.MIN_VALUE要单独处理,不要直接取绝对值,否则直接溢出,应该返回0;第二就是要判断是否有

res * 10 + posx % 10 > Integer.MAX_VALUE

但是不能直接这么写,直接这样写从左向右执行code也会溢出,可以换一种写法写成判断是否有

res > (Integer.MAX_VALUE - posx % 10) / 10
如果是直接返回0.最后当x位负数时,返回结果的相反数。


AC Code

public class Solution {
    public int reverse(int x) {
        //1259
        if(x == Integer.MIN_VALUE){
            return 0;//Integer.MIN_VALUE is -2^31, the abs of which is larger than Integer.MAX_VALUE(2^31 - 1)
        }
        int posx = Math.abs(x);
        int res = 0;
        while(posx != 0){
            int rem = posx % 10;
            //see whether res * 10 + posx % 10 > Integer.MAX_VALUE if yes, overflow
            //note that we move the item except res in the right to the left
            if(res > (Integer.MAX_VALUE - rem) / 10){
                return 0;
            }
            res = res * 10 + rem;
            posx /= 10;
        }
        return x>0?res:-res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值