leetcode刷题之-整数反转

又开始刷题了,最近在刷这题

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

x=1534236469

输出0;

需要考虑溢出的情况,个人觉得可以不用 Long 来写,毕竟需要占额外的内存分配

//第一次写,没判断仔细
   public static int reverse(int x) {
        boolean isNegative = x < 0;
        int result = 0;
        int position = Math.abs(x);
        while(position!=0){
            int  temp = position % 10;
            if(result>(Integer.MAX_VALUE-temp)/10){
                return 0;
            }
            System.out.println("temp:"+temp);
            position = position / 10;
            result = result * 10 + temp;
        }

        return isNegative?-result:result;
    }


// 这个方法太巧妙了,前人栽树,后人乘凉

    public int reverse(int x) {
        int result = 0;
        while(x != 0) {
            int tmp = result; // 保存计算之前的结果
            result = (result * 10) + (x % 10);
            x /= 10;
            // 将计算之后的结果 / 10,判断是否与计算之前相同,如果不同,证明发生溢出,返回0
            if (result / 10 != tmp) return 0; 
        }

        return result;
    }
int reverse(int x){
    int max = 0x7fffffff;
    long b = 0;
    while (x != 0) {
        b = b * 10 + x % 10;
        x = x / 10;
    }
    return (b > max || b < (-1 * (max + 1))) ? 0 : b;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值