【问题标题】:Java Integer Max Range multiplicationJava整数最大范围乘法
【发布时间】:2015-03-05 06:03:45
【问题描述】:
Integer num = 2147483647;
Integer res =  num * num;
System.out.println(res);

上面的输出是 1。我不知道为什么。谁能解释一下。

提前致谢。

【问题讨论】:

  • 溢出........
  • 整数的有限范围为 2^32-1... 大约 20 亿
  • 2^32-1 用于无符号整数,(2^32-1)/2 用于有符号整数
  • 让我重新表述我的问题。我知道它超出了整数的范围。但是为什么结果是一个。什么逻辑?我查看了 Integer.java 类,但没有发现任何有用的东西。

标签: java


【解决方案1】:

这应该说明为什么结果 = 1:

    long x = Integer.MAX_VALUE;
    long y = Integer.MAX_VALUE;
    long res = x * y;
    System.out.println(Long.toHexString(res));

打印

3fffffff00000001

如果我们将 res 转换为 int,我们将得到 1

【讨论】:

    【解决方案2】:

    这是因为整数溢出。 Java 的最小值为 -2,147,483,648,最大值为 2,147,483,647(含),并且您的结果(res)超出了 Integer 最大范围。

    【讨论】:

      【解决方案3】:

      这是因为标志值
      0: iconst_0
      1: istore_1

      由于Integer 的限制超出范围,它将设置1 的标志以了解更多关于use this link 工作原理的信息

      【讨论】:

        【解决方案4】:

        这是因为它超出了整数甚至长整数的范围,即-2,147,483,648和最大值2,147,483,647(含)之间。

        如果是这种情况,您应该尝试使用 BigInteger:

        String num = "2147483647";
        BigInteger mult = new BigInteger(num);
        System.out.println(mult.multiply(mult));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-07-14
          • 1970-01-01
          • 2015-02-18
          • 1970-01-01
          • 1970-01-01
          • 2016-03-31
          • 1970-01-01
          相关资源
          最近更新 更多