Leetcode习题-Reverse Integer

本文详细探讨了整数反转算法的核心实现过程,包括处理正负数、末尾为0的情况以及可能的溢出问题。通过实例分析,阐述了如何在不同边界条件下正确实现整数反转,并提供了代码实现及测试验证。

Reverse Integer
 
AC Rate: 2538/6177
My Submissions

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).


 拿个test边写代码边比较结果是否与预期一致,很高兴把些精度不对的问题解决后一次过了。


    public int reverse(int x) {
        int isNegative = x < 0? -1 : 1;
        
        long n = isNegative*x;
        
        long result = 0;
        
        long tmp = 1;
        
        while( n / tmp > 0 ){
            long prev = tmp;
            tmp *= 10;
            long k = ( n % tmp ) / prev;
            result = result*10 + k;
        }
        
        return (int)result*isNegative;
    }





评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值