Reverse Integer java

本文详细介绍了如何通过算法实现整数的反转,并给出了两种不同的实现方式。第一种方法使用绝对值函数,而第二种方法直接处理输入整数。此外,还特别注意了边界条件的处理,确保反转后的结果不会超出整数范围。

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

class Solution {
    public int reverse(int x) {
        long res = 0;
        int tmp = Math.abs(x);
        while(tmp > 0){
            res = res * 10 + tmp % 10;
            if(res > Integer.MAX_VALUE){
                return 0;
            }
            tmp / = 10;
        }
        return (int)(x>=0?res:-res);
    }
}

在看了网上的解法后,自己写了一遍总是不对,后来发现是倒数第二行代码中“/”和“=”之间加了个空格导致的。

解法二(我自己写的)

class Solution {
    public int reverse(int x) {
        long res = 0;
        //int tmp = Math.abs(x);
        while(x != 0){
            res = res * 10 + x % 10;
            if(res > Integer.MAX_VALUE|| res < -Integer.MAX_VALUE){
                return 0;
            }
            x /= 10;
        }
        return (int)(res);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值