Leetcode刷题之旅--7. 整数反转(反转有符号整数)

先来看下题目要求Leetcode刷题之旅--7. 整数反转(反转有符号整数)_第1张图片

开搞
一开始没考虑到溢出,解答错误。
考虑了溢出之后得到

public class Solution {
    public static void main(String[] args) {
        System.out.println(new Solution().reverse(-2147483412));
    }

    public int reverse(int x) {
        int bits = 0;
        boolean flag = false;
        int result = 0;
        String s = "" + x;
        bits = s.length();
        if (x < 0) {
            bits -= 1;
            flag = true;
            x = -x;
        }
        for (int i = 0; i < bits; i++) {
            result = result * 10 + x % 10;
            x /= 10;
            if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && x % 10 > 7)) {
                return 0;
            }
            if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && x % 10 < -8)) {
                return 0;
            }
        }
        if (flag) {
            result = -result;
        }
        return result;
    }
}

最终得到的结果是错误。由于思维固化了,一心想得到数字的位数于是转化为字符串得到位数,观摩了官方答案后才恍然大悟,原来只需要一直判定x/10==0就能完成循环的判定。对比了官方答案反思后得出for循环由转成string得到的位数和x/10后while(x!=0)的循环次数造成了result的结果判定出了问题。修改了半天还是有问题,心态小崩,还是换为官方的while循环了。
附上官方解答:

public class Solution {
    public static void main(String[] args) {
        System.out.println(new Solution().reverse(-2147483412));
    }


    public int reverse(int x) {
       int rev = 0;
       while (x != 0) {
           int pop = x % 10;
           x /= 10;
           if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
           if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
           rev = rev * 10 + pop;
       }
       return rev;
   }
}

你可能感兴趣的:(Leetcode刷题之旅--7. 整数反转(反转有符号整数))