我正在尝试从 BigInteger 类中实现我自己的 add() 方法版本。到目前为止,当给定两个相同长度的数字时,它可以完美地工作,但是当给定两个不同长度的数字时,它无法编译(索引超出范围)。解决这个问题的最佳方法是什么?
如果有帮助,当两个值相加为 10 和 1 时的输出为 20。
public BigInt add(BigInt b) {
int[] ans = new int[value.length];
int carry=0;
if(this.lessThan(b))
for(int i=b.value.length-1;i>=0;i--){
int result=this.value[i]+b.value[i]+carry;
carry=result/10;
result%=10;
ans[i]=result;
}
else
for(int i=this.value.length-1;i>=0;i--){
int result=this.value[i]+b.value[i]+carry;
carry=result/10;
result%=10;
ans[i]=result;
}
String ANSsz=convertArrayToString(ans);
BigInt Sum = new BigInt(ANSsz);
return Sum;
}