Java-整数反转-20190419

0.题目描述

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:输入: 123 输出: 321
示例 2:输入: -123 输出: -321
示例 3:输入: 120 输出: 21
注意:假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

1.我的解法

1.1 总体的思路是:

  • 如果是正整数,利用%10和/10的方式,不断取出对应位置上的数字,并且赋值到字符串str的尾部;最后,Integer.parseInt方法转化为正整数并返回,如果报NumberFormatException,则表示溢出,返回0;
  • 如果是负整数,先取绝对值,然后按照%10和/10的方式,不断取出对应位置上的数字,同样添加到字符串上;最后转化为正整数,添加负号并返回,如果报错同样表示溢出,返回0;

1.2 代码

public int reverse(int x) {
        int result;
        int temp = x;
        String temp_result="";
        try {
            if (temp > 0) {
                while (temp / 10 >= 0 && temp != 0) {
                    temp_result += (temp % 10);
                    temp /= 10;
                }
                result = Integer.parseInt(temp_result);
            } else {
                temp = Math.abs(x);
                while (temp / 10 >= 0 && temp != 0) {
                    temp_result += (temp % 10);
                    temp /= 10;
                }
                result = -Integer.parseInt(temp_result);
            }
        }catch(NumberFormatException e){
            result=0;
        }
        return result;
    }

1.3 结果
我的解法
这样的方法,时间复杂度为O(log10(x)),空间复杂度为O(1).应付当前这个问题,显然是能够解决的。但是,很明显,代码有值得优化的地方。

2.LeetCode给出的解法

public static int reverse(int x) {
        int rev = 0;//rev存储反转的数字
        while(x!=0){
            int pop = x%10;//pop表示弹出的数
            //如果已经反转内容rev大于Integr最大值/10,那么一定溢出;
            // 如果最rev反转内容等于最大值/10且最后一位pop的数字大于7,那么就从正数这边溢出了
            //另外一种就是从负数那边溢出了
            if((rev>Integer.MAX_VALUE/10||(rev==Integer.MAX_VALUE/10&&pop>7))
                    ||rev<Integer.MIN_VALUE/10||(rev==Integer.MIN_VALUE/10&&pop<-8)){
                return 0;
            }
            rev=rev*10+pop;//把pop防到rev后面
            x/=10;//去掉已经pop的内容
        }
        return rev;
    }

这种方法的结果:
官方解法
效果更好,时间复杂度为O(log10(x)),空间复杂度O(1)。

猜你喜欢

转载自blog.csdn.net/qq_32760017/article/details/89410058