所以我正在为一个我正在做的课程的项目工作,我正在编写一个方法,需要将两个包含整数的ArrayLists一起添加,并在新的ArrayList中设置总和。目前我有这个,工作正常
public BigInt add(BigInt otherBigInt) {
BigInt result = new BigInt();
int length = digitList.size() - 1;
int lengthOther = otherBigInt.digitList.size() - 1;
int temp = 0;
int whole = 0;
int carry = 0;
for (int i = length; i >= 0; i--){
temp = (digitList.get(i) + otherBigInt.digitList.get(i));
temp += carry;
// temp is equal to the sum of this(i) and otherBigInt(i), plus any number carried over.
if (temp >= 10){
whole = temp - 10;
carry = 1;
result.digitList.add(whole);
}
else if (temp < 10){
carry = 0;
result.digitList.add(temp);
}
}
if (carry == 1){
result.digitList.add(carry);
}
//adds any remaining carried number after for loop
// Supply this code.
return result;
}
但是,目前该方法仅在arrayLists具有相同大小时才有效,如何修改方法以适应不同大小的列表?一个例子是两个包含735934和68945的列表,给出结果804879。
P.S。 不确定是否需要,(在这里发布还是新的)但我正在添加的两个列表是7359和6894,给出答案14253.
答案 0 :(得分:0)
让两位数字为a1[0 ... n1]
和a2[0 ... n2]
。现在你的算法就像:
add(a1, a2):
min_length = min{a1.length, a2.length}
result[0 ... max{a1.length, a2.length} + 1]
carry = 0
for(i in [0 ... min_length - 1])
result[i] = carry + a1[i] + a2[i]
carry = result[i] / 10
result[i] %= 10
while(i < a1.length)
result[i] = a1[i]
while(i < a2.length)
result[i] = a2[i]
result[i] = carry
请注意,您必须添加剩余的数字,以防它们的大小不同。我假设数字按顺序存储,即a[0]
是第一位数。
答案 1 :(得分:0)
如果我的假设是正确的,那么您正在尝试模拟使用两个列表添加两个数字的情况,其中数字的一个数字占据列表的一个索引。
最简单的解决方案是假设最短的列表没有值,而是添加到两个列表的最大值:
public BigInt add(BigInt otherBigInt) {
BigInt result = new BigInt();
int length = Math.max(digitList.size(), otherBigInt.digitList.size()) - 1;
int lengthOther = otherBigInt.digitList.size() - 1;
int temp = 0;
int whole = 0;
int carry = 0;
for (int i = length; i >= 0; i--){
temp = ( checkAndGet(digitList, i) + checkAndGet(otherBigInt.digitList, i) );
temp += carry;
// temp is equal to the sum of this(i) and otherBigInt(i), plus any number carried over.
if (temp >= 10) {
whole = temp - 10;
carry = 1;
result.digitList.add(whole);
}
else {
carry = 0;
result.digitList.add(temp);
}
}
if (carry == 1){
result.digitList.add(carry);
}
//adds any remaining carried number after for loop
// Supply this code.
return result;
}
// if the index position being retrieved is larger than the size, assume 0
private int checkAndGet(List<Integer> input, position) {
return (input.size() < position) ? input.get(position) : 0;
}
答案 2 :(得分:0)
我将向后遍历较小的数组,随时将索引添加到一起:
ArrayList<Integer> toIterate = (array1.size() > array2.size)? a1 : a2;
ArrayList<Integer> seperate = (array1.size() > array2.size)? a2 : a1;
for (int i = toIterate.size - 1; i >= 0; i --) {
if (seperate.get(i) != null) {
arrayResult.add(toIterate.get(i) + seperate.get(i));
}
else {
arrayResult.add(toIterate.get(i));
}
}