我编写了这个方法,它在 arrayList 中搜索是否有两个数字之和等于变量 elem。问题是变量的总和超过了 long 类型的维度。怎么写呢?
public static boolean searchSum(ArrayList<Long> array, long elem) {
int left = 0, right = array.size()-1;
while (left<right) {
long n1=Long.valueOf(array.get(left));
long n2=Long.valueOf(array.get(right));
if ((n1+n2)==elem) return true;
else if ((n1+n2)<elem) left++;
else right--;
}
return false;
}
最佳答案
您可以使用 java.math.BigInteger
.它可以存储不可变的任意精度整数。
例如:
public BigInteger sum(Long number1, Long number2) {
BigInteger bigNumber1 = BigInteger.valueOf(number1);
BigInteger bigNumber2 = BigInteger.valueOf(number2);
BigInteger result = bigNumber1.add(bigNumber2);
return result;
}
在这种情况下,你可以这样重写这个方法:
public static boolean searchSum(ArrayList<Long> array, long elem) {
BigInteger bigElem = BigInteger.valueOf(elem);
int left = 0, right = array.size() - 1;
while (left < right) {
BigInteger n1 = BigInteger.valueOf(array.get(left));
BigInteger n2 = BigInteger.valueOf(array.get(right));
BigInteger sum = n1.add(n2);
if (sum.equals(bigElem)) {
return true;
} else if (sum.compareTo(bigElem) < 0) {
left++;
} else {
right--;
}
}
return false;
}
关于java - 在 Java 中总结两个巨大的长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50160038/