美文网首页
[LeetCode] 7. Reverse Integer (e

[LeetCode] 7. Reverse Integer (e

作者: LittleSasuke | 来源:发表于2018-04-17 16:46 被阅读9次

Welcome To My Blog

7. Reverse Integer (easy)

7.1.png
  1. 在java中,数值溢出后还能计算,只不过得到的计算结果不正确,可以设置两个变量并利用这一点进行溢出判断
    7.3.png
    7.2.png
  2. 因为在res = res * 10 + curr;形式下,0没有贡献,所以不用专门处理leading 0
  3. 可以保留符号运算,负数+负数或者正数+正数,带符号运算时要注意循环条件是 x != 0,而不是x > 0
  4. 题目要求溢出时返回0,在处理上与溢出时返回Max或Min有所不同
  5. 按照一般情况和边界情况讨论
    • 一般情况: -123
    • 边界情况: 120,100100,翻转后溢出
      • 最高位取值范围[1,9],个位取值范围[0,9]
      • 保留符号
      • 避免0开头
      • 避免溢出

原始版本,正负数,leading 0以及判断溢出都不够简洁

    public static int reverse(int x) {
        int res = 0, curr = 0, sign = 1;
        //1. 提取符号
        sign = sign * x < 0 ? -1 : 1;
        //2. 转化为正数
        x = x * sign;
        while ( x > 0){
            //3. 当前的数字
            curr = x % 10;
            //4.1 个位数前面有几个数就要乘几次10;
            //4.2 十位数前面有几个数就要成几次10;同理...
            x /= 10;
            //5 avoid overflow
            boolean overflow =(res > Integer.MAX_VALUE / 10) || res == Integer.MAX_VALUE / 10 && (curr > Integer.MAX_VALUE % 10 || curr*sign < Integer.MIN_VALUE % 10 ) ;
            if (overflow) return 0;

            res = res * 10 + curr;
        }
        return res * sign;
    }

最优解

    public static int reverse(int x) {
        int res = 0;
        // 带符号运算的话这里得是 x!=0
        while (x != 0){
            int curr = x % 10;
            int tempRes = res * 10 + curr ;
            // if overflow?
            if((tempRes -curr) / 10 != res) return 0;
            res = tempRes;
            x /= 10;
        }
    return res;
    }

相关文章

网友评论

      本文标题:[LeetCode] 7. Reverse Integer (e

      本文链接:https://www.haomeiwen.com/subject/fwlpkftx.html