This question already has answers here:
How can I detect integer overflow on 32 bits int?
                                
                                    (5个答案)
                                
                        
                                在10个月前关闭。
            
                    
我需要从头开始创建parseInt方法,到目前为止,我已经明白了。唯一的问题是我很难弄清楚如何找出一个int变量是否溢出或下溢,以及是否要在Java中抛出IllegalArgumentException。

为了更好地理解,这是我的任务:

创建静态方法parseInt(String),将字符串转换为int值(正数或负数)。当...时,方法抛出IllegalArgumentException。


字符串中包含除“-”以外的非数字字符(作为字符串的第一个字符)。
字符串只有“-”,没有数字。
字符串表示一个太大的数字,无法存储为整数并产生溢出
字符串代表的数字太小而无法存储为整数并产生下溢


这是我到目前为止的

 /**
 * Convert a string into an integer value
 * @param str The string to be converted
 * @return answer
 * @throws IllegalArgumentException if answer is underflowing or overflowing
 */
public static int parseInt(String str) throws IllegalArgumentException {
    int answer = 0, factor = 1;
    int i = 0;
    for (i = str.length()-1; i >= 0; i--) {
        answer += (str.charAt(i) - '0') * factor;
        factor *= 10;
    }

    boolean isNegative = false;
    if(str.charAt(0) == '-') {
        isNegative = true;
    }

    if (answer > Integer.MAX_VALUE) throw new IllegalArgumentException();
    if (answer < Integer.MIN_VALUE) throw new IllegalArgumentException();

    if (isNegative) {
        answer = -answer;
    }

    return answer;
}

最佳答案

这样就无需使用long

public static int parseInt(String str) throws IllegalArgumentException {
    int answer = 0, factor = 1;

    boolean isNegative = false;
    if(str.charAt(0) == '-') {
        isNegative = true;
    }

    for (int i = str.length()-1; i >= (isNegative ? 1 : 0); i--) {
        int nextInt = (str.charAt(i) - '0') * factor;

        if(isNegative && answer > Math.abs(Integer.MIN_VALUE + nextInt))
            throw new IllegalArgumentException();
        else if(!isNegative && answer > Integer.MAX_VALUE - nextInt)
            throw new IllegalArgumentException();

        answer += nextInt;
        factor *= 10;
    }

    if (isNegative) {
        answer = -answer;
    }

    return answer;
}

10-08 17:09