【LeetCode_整数_取余运算】7. 整数反转


题目描述

7. 整数反转

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

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

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

输入:x = 123
输出:321

考察点

第一次:2022年12月12日09:28:08

整数转化为字符串,字符串翻转

整数转化为字符串,这样字符串就可以倒序遍历得到字符串,再把字符串变为数字。

那么,如果有负数的情况,就先把负整数转化为正整数,然后再把字符串在第0个位置上添加上 ‘-’ ;

除此之外呢,“反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。”,也就是如果字符串转为为数字发生异常,我们就返回0;

最终,把思路转化为代码如下:

代码展示

class Solution {
    public int reverse(int x) {

        boolean isNegative = false;
        if (x < 0){
            isNegative = true;
            x = x * -1;
        }
        
        String before = String.valueOf(x);
        StringBuilder after = new StringBuilder();
        for (int i = before.length()-1; i >= 0; i--) {
            after.append(before.charAt(i));
        }
        Integer result = new Integer("0");
        if(isNegative){
            after.insert(0, '-');
        }
        try {
            result = new Integer(after.toString());
        }catch (NumberFormatException e ){

        }
        return result;
    }

    /**
     * @Result:
     * 
     * 执行结果:通过
     * 执行用时:1 ms, 在所有 Java 提交中击败了 43.83% 的用户
     * 内存消耗:39.2 MB, 在所有 Java 提交中击败了 13.45% 的用户
     *
     * 2022/12/12 10:10
     */
}

唉,我也想到了这个取余运算,在我运算的思路中:例如 123的数字。

我想到的就是 123%100,其实 只要去取余10 就行了。
然后把余数3 拼装成结果result,我想到的是 result = result + 余数 * 100,其实只要 result = result * 10 + 余数

取余运算

图解 7. 整数反转

取余运算:
在这里插入图片描述
判断整数溢出:

res每次更新后除10,然后跟上一次的res比较一下,如果不相等,就是溢出

class Solution {

    public int reverse(int x) {
        int result = 0;
        int last = 0;
        while (x != 0) {
            //每次取末尾数字
            int tmp = Math.abs(10);
            last = result;
            result = result * 10 + tmp;
            //判断整数溢出
            if (last != result / 10) {
                return 0;
            }
            x /= 10;
        }
        return result;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(Integer.MAX_VALUE); // 2147483647
        System.out.println(Integer.MAX_VALUE + 10); // -2147483648
        System.out.println(solution.reverse(1147483649)); // 0
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值