xyooyx
V2EX  ›  LeetCode

这次是整数反转,菜鸡的我又看不懂解法了

  •  
  •   xyooyx · Jan 11, 2019 · 12063 views
    This topic created in 2682 days ago, the information mentioned may be changed or developed.

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

    示例 1:

    输入: 123
    输出: 321
    

    假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

    以下是别人的解答

    public static int reverse(int x) {
            int num = 0;
            while (x != 0) {
                int n = x % 10;
                System.out.println(n);
                x /= 10;
                if (num < Integer.MIN_VALUE / 10 || (num == Integer.MIN_VALUE / 10 && n < -8)) {
                    return 0;
                }
    
                if (num > Integer.MAX_VALUE / 10 || (num == Integer.MAX_VALUE / 10 && n > 7)) {
                    return 0;
                }
    
                num = num * 10 + n;
            }
            return num;
        }
    

    为什么能通过以上两个 if 内容判数值断溢出

    以下是两个常量的定义

       MIN_VALUE = 0x80000000;
       
       MAX_VALUE = 0x7fffffff;
    
    1 replies    2019-02-06 23:40:34 +08:00
    flewsea
        1
    flewsea  
       Feb 6, 2019 via Android
    它是在最后一位加上去前进行判定的,所以把最大值跟最后一位分别判定下就行,至于为什么这时候判定,因为如果加上去,那就有可能溢出了,失去了判定的意义
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2993 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 69ms · UTC 07:31 · PVG 15:31 · LAX 00:31 · JFK 03:31
    ♥ Do have faith in what you're doing.