检查 int 变量是否在 Java 中溢出或下溢

我需要从头开始创建一个 parseInt 方法,到目前为止我已经明白了。唯一的部分是我无法弄清楚如何确定一个 int 变量是溢出还是下溢,如果它是然后在 Java 中抛出 IllegalArgumentException。

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

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

  1. 字符串包含除“-”之外的非数字字符(作为字符串的第一个字符)。

  2. 字符串只有 '-' 而没有数字。

  3. 字符串表示一个太大而无法存储为整数并产生溢出的数字

  4. 字符串表示一个数字太小而不能作为整数存储并产生下溢

这是我到目前为止所拥有的

 /**

 * 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;

}


红颜莎娜
浏览 114回答 1
1回答

qq_花开花谢_0

这不需要使用longpublic static int parseInt(String str) throws IllegalArgumentException {&nbsp; &nbsp; int answer = 0, factor = 1;&nbsp; &nbsp; boolean isNegative = false;&nbsp; &nbsp; if(str.charAt(0) == '-') {&nbsp; &nbsp; &nbsp; &nbsp; isNegative = true;&nbsp; &nbsp; }&nbsp; &nbsp; for (int i = str.length()-1; i >= (isNegative ? 1 : 0); i--) {&nbsp; &nbsp; &nbsp; &nbsp; int nextInt = (str.charAt(i) - '0') * factor;&nbsp; &nbsp; &nbsp; &nbsp; if(isNegative && answer > Math.abs(Integer.MIN_VALUE + nextInt))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalArgumentException();&nbsp; &nbsp; &nbsp; &nbsp; else if(!isNegative && answer > Integer.MAX_VALUE - nextInt)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalArgumentException();&nbsp; &nbsp; &nbsp; &nbsp; answer += nextInt;&nbsp; &nbsp; &nbsp; &nbsp; factor *= 10;&nbsp; &nbsp; }&nbsp; &nbsp; if (isNegative) {&nbsp; &nbsp; &nbsp; &nbsp; answer = -answer;&nbsp; &nbsp; }&nbsp; &nbsp; return answer;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java