程序:-我必须从数组中查找第二大元素,时间复杂度应为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);
}
}
}
BigInteger bigInt = new BigInteger(str);
int num = bigInt.intValueExact();
这些值-214748364800,-214748364801完全超出int值的范围。整数范围在-2147483648和2147483647之间
您的代码中的问题在这里,因为int的限制远小于1024位数字。
BigInteger bigInt = new BigInteger(str);
int num = bigInt.intValueExact();
如果您确实需要使用如此大的数字,则可能必须编写自己的BigInteger版本,该版本使用其他方式存储其值,从而允许更多的存储空间。也许像这样的二维数组:int [] []存储,因为它可以保存最大2 ^(2 ^(2 ^ 32-1)-1)的值。有关更多信息,您可以看到此documentation