07整数反转

思路

很简单的一道题
所以没啥好说的

class Solution {

    public int reverse(int x) {

        if(x>0)

        {

            int temp=0;

            try{

                while(x>0)

                {

                    temp=temp*10+x%10;

                    x=x/10;

                }

                return temp;

            }

            catch(Exception e){

                return 0;

            }

        }

        else

        {

            int temp=0;

            try{

                x=x*-1;

                while(x>0)

                {

                    temp=temp*10+x%10;

                    x=x/10;

                }

                return temp*-1;

            }

            catch(Exception e){

                return 0;

            }

        }

    }

}

其实小于0大于0可以合并没有影响

class Solution {

    public int reverse(int x) {

            long temp=0;

            try{

                while(x!=0)

                {

                    temp=temp*10+x%10;

                    x=x/10;

                }

                return (int)temp;

            }

            catch(Exception e){

                return 0;

            }

    }

}

但是这个try-catch模块在这里用不了为什么呢
因为java中一旦发生整数溢出,他会自动回来,反正就拿这个测试用例来看
外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
其实通过的相当多,就是差那么几个
特殊的
就会有问题

class Solution {
    public int reverse(int x) {
        // 定义变量来存储反转后的整数
        long temp = 0; // 使用long类型以避免在while循环中发生溢出
        while (x != 0) {
            temp = temp * 10 + x % 10;
            x = x / 10;
            
            // 检查是否超出32位有符号整数范围
            if (temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) {
                return 0;
            }
        }
        // 将long类型转换回int类型
        return (int) temp;
    }
}

这个才是正确的

诶其实try-catch也能用不过看具体情况

只能说不知道了

麻了

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Xia0Mo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值