7. 整数反转

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

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

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

示例 1:

输入:x = 123
输出:321
示例 2:

输入:x = -123
输出:-321
示例 3:

输入:x = 120
输出:21
示例 4:

输入:x = 0
输出:0

         我们尝试用数学的做法,就是那个《秦九韶算法》。

从个位开始,一位一位取数字 

从个位开始,循环加上对应位上的数字 

当我们只用 int 来存结果 res 时,要考虑溢出的问题。因为

java.lang.Integer public static final int MAX_VALUE = 2147483647

java.lang.Integer public static final int MIN_VALUE = -2147483648

1147483649 一反转,就溢出了。

当用 int 来存结果的时候,要判断是否溢出,可以这样写:

r 大于 Integer.MAX_VALUE

r 小于 Integer.MIN_VALUE 

 (图中的 x 是简写的,就是那个意思)

用int 来存结果的写法(推荐这个)

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

  用 long 来存结果的写法

public class Solution {
    public int reverse(int x) {
        long res = 0;
        while(x != 0){
            res = res * 10 + x % 10;
            x /= 10;
        }
        if (res > Integer.MAX_VALUE) return 0;
        if (res < Integer.MIN_VALUE) return 0;
        return Integer.parseInt(Long.toString(res));
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

可持续化发展

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

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

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

打赏作者

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

抵扣说明:

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

余额充值