[LintCode] Reverse Integer

本文介绍了一种有效的整数反转算法,特别关注了符号位处理及32位整数溢出问题。通过具体示例和代码实现,展示了如何避免在反转过程中出现的潜在错误。

Problem

Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).

Example

Given x = 123, return 321

Given x = -123, return -321

Note

这道题有一些细节需要留意。新数res会不会溢出?符号位如何处理?
用惯用的做法,n除以10取余,得到最低位cur,放进res。每次循环res乘以10累加当前最低位cur,同时n除以10不断减小。
要点在于考虑res乘10累加运算的情况,用分支语句判断发生溢出的条件。不能直接写if (res * 10 + cur > Integer.MAX_VALUE),因为res * 10就有可能会溢出了;而要用(Integer.MAX_VALUE - cur) / 10,因为只有减法和除法,结果不可能溢出。
最后的结果要加上之前排除的符号位。

Solution

public class Solution {
    public int reverseInteger(int n) {
        boolean isNeg = n < 0;
        n = isNeg ? -n : n;
        int res = 0;
        while (n != 0) {
            int cur = n % 10;
            if (res >= (Integer.MAX_VALUE - cur) / 10) return 0;
            res = res * 10 + cur;
            n /= 10;
        }
        return isNeg ? -res : res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值