[英]Sum two enormous long in Java
I wrote this method which search in the arrayList if there are two numbers which sum equals the variable elem . 我写了这个方法,它在arrayList中搜索是否有两个总和等于变量elem的数字 。 The problem is that the sum of the variable exceed the dimension of the long type. 问题在于变量的总和超过了long类型的维数。 How can I write it? 我该怎么写?
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;
}
You can use java.math.BigInteger
. 您可以使用java.math.BigInteger
。 It can store immutable arbitrary-precision integer. 它可以存储不可变的任意精度整数。
For example: 例如:
public BigInteger sum(Long number1, Long number2) {
BigInteger bigNumber1 = BigInteger.valueOf(number1);
BigInteger bigNumber2 = BigInteger.valueOf(number2);
BigInteger result = bigNumber1.add(bigNumber2);
return result;
}
In this case, you can rewrite this method like this: 在这种情况下,您可以这样重写此方法:
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;
}
我建议通过添加单个数字来编写它,如果它等于或大于长长度,则将其分成两个long或一个数组,并以这种方式访问数字以进行更长的数学运算。
You don't need BigInteger
to tell the sum of two like signed numbers (here: long
s) overflowed. 您不需要BigInteger
来告诉两个相似的有符号数字(此处为long
s)溢出的总和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.