java.lang.ArithmeticException:BigInteger超出int范围[关闭]

问题描述 投票:-1回答:3
我正在学习Java,并且正在尝试一些小程序。我对此有疑问:

程序:-我必须从数组中查找第二大元素,时间复杂度应为O(n),如果没有找到,返回“ -1”。

但是我遇到以下例外:

线程“主”中的异常java.lang.ArithmeticException:BigInteger超出java.math.BigInteger.intValueExact的int范围

注意:-整数字符串的最大长度可以是2 ^ 10 = 1024位数字

public class GetSecondLargeElement { public static void main(String[] args) { // test case not working String[] arr = {"-214748364800", "2", "-214748364801"}; // Below test cases are working fine... /*String[] arr = {"3", "-2"}; String[] arr = {"5", "5", "4", "2"}; String[] arr = {"4", "4", "4"}; String[] arr = {}; String[] arr = {"3", "", "-4", ""};*/ System.out.println("secong largest no : " + getSecondMaxValue(arr)); } /** * Get Second Maximum Number * * @param arr Array of String type * @return String */ private static String getSecondMaxValue(String arr[]) { if (arr == null || arr.length == 0) { return "-1"; } int firstVal = Integer.MIN_VALUE, secondVal = Integer.MIN_VALUE; for (String str : arr) { if (str == null || str.isEmpty()) { continue; } long count = str.chars().filter(Character::isDigit).count(); if (count > 1024) { continue; } BigInteger bigInt = new BigInteger(str); int num = bigInt.intValueExact(); if (num > firstVal) { secondVal = firstVal; firstVal = num; } else if (num > secondVal && num != firstVal) { secondVal = num; } } if (secondVal == Integer.MIN_VALUE) { return String.valueOf((secondVal = -1)); } else { return String.valueOf(secondVal); } } }
java algorithm sorting data-structures biginteger
3个回答
0
投票
您的问题在这里:

BigInteger bigInt = new BigInteger(str); int num = bigInt.intValueExact();

这些值-214748364800,-214748364801完全超出int值的范围。整数范围在-2147483648和2147483647之间

0
投票
整数字符串显然超出范围,整数可以有32位,其中1位分配给符号,即负或正整数。

0
投票
BigInteger使用int []来存储数组的值。这意味着该数字不能大于2 ^(Integer.Max_Value),因为任何大于该值的值都会使数组的索引(存储在单个int中)大于数组的最大大小。

您的代码中的问题在这里,因为int的限制远小于1024位数字。

BigInteger bigInt = new BigInteger(str); int num = bigInt.intValueExact();

如果您确实需要使用如此大的数字,则可能必须编写自己的BigInteger版本,该版本使用其他方式存储其值,从而允许更多的存储空间。也许像这样的二维数组:int [] []存储,因为它可以保存最大2 ^(2 ^(2 ^ 32-1)-1)的值。

有关更多信息,您可以看到此documentation

© www.soinside.com 2019 - 2024. All rights reserved.