【问题标题】:Check if a int variable is overflowing or underflowing in Java [duplicate]检查Java中的int变量是否溢出或下溢[重复]
【发布时间】:2019-05-17 00:38:22
【问题描述】:

我需要从头开始创建一个 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;
}

【问题讨论】:

  • int 值不可能大于 Integer.MAX_VALUE 也不能小于 Integer.MIN_VALUE,因为它们定义了 int 可以容纳的最大值和最小值。
  • @another-dave 是的,我意识到了这一点。但那我怎么能呢?
  • 我会选择long answer,而不是int answer,然后在返回时将其转换为int
  • 确实,如果a+b
  • 我不喜欢“长答案”的解决方案,因为如果我要求您生成 parseLong,则不会有从您的 parseInt 解决方案到 parseLong 解决方案的简单映射(好吧,我假设你可以使用 bignums,但仍然......)

标签: java


【解决方案1】:

这样做不使用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;
}

【讨论】:

    猜你喜欢
    • 2012-11-19
    • 2019-01-23
    • 2011-01-24
    • 1970-01-01
    • 2011-09-18
    • 2017-09-13
    • 1970-01-01
    • 2016-05-22
    相关资源
    最近更新 更多