Java整数溢出

Java integer overflow

我是 Java 的新手,我正在 Leetcode 上实现一个将字符串转换为整数的简单函数。

public int myAtoi(String str) {
    if(str.length() == 0){
        return 0;
    }
    str = str.trim();
    int n = str.length();

    int signal = 0;
    if(n == 1 && str.equals("+") || str.equals("-")){
        return 0;
    }
    if(str.charAt(0) == '+'){
        signal = 1;
    }else if(str.charAt(0) == '-'){
        signal = -1;
    }

    int i = (signal != 0)? 1 : 0;
    if(signal == 0){
        signal = 1;//default
    }

    int res = 0;
    while(i < n){
        char c = str.charAt(i);
        if(!Character.isDigit(c)){
            return res * signal;
        }
        //res = res * 10 + c - '0';
        if(signal * res > Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        if(signal * res < Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }
        res = res * 10 + c - '0';
        ++i;
    }
    return res * signal;
}

我知道 java 整数有 2147483647MAX_VALUE。当我的输入是 2147483648 时,输出应该是 2147483647 但实际上是 -214748648。我真的不知道这里出了什么问题。谁能帮助我理解这一点?

输入永远不会是 +2147483648,因为该值不能表示为 Java 整数。

它会环绕到您观察到的负数,因此请考虑该结果。

考虑这个例子

public static void main(String args[]) {
    int i=2147483647;
    System.out.println("i="+i);
    int j=++i;
    System.out.println("Now i is="+i);
    System.out.println("j="+j);
}

会发生什么? 输出将是:

i = 2147483647
Now i is=-2147483648
j=-2147483648

整数最大值为2,147,483,647,最小值为-2,147,483,648。在 j 中(post 增量 i),我们已经超过整数的最大限制

这也正是您的情况。

因为整数溢出。当它溢出时,下一个值是Integer.MIN_VALUE

为什么?

Integer values are represented in binary form, and there is binary addition in java. It uses a representation called two's complement, in which the first bit of the number represents its sign. Whenever you add 1 to the largest Integer(MAX INT), which has a bit sign of 0, then its bit sign becomes 1 and the number becomes negative.

因此,不要将 > MAX INT 作为输入,否则请在您的代码中添加条件以检查输入本身。