Java 实现BigInt.add()?
我试图从BigInteger类实现我自己版本的add()方法。到目前为止,当给定两个长度相同的数字时,它可以完美地工作,但当给定两个长度不同的数字时,它无法编译(索引超出范围)。解决这个问题的最好办法是什么 如果有帮助,两个值相加时的输出是10,1是20Java 实现BigInt.add()?,java,implementation,biginteger,bigint,indexoutofboundsexception,Java,Implementation,Biginteger,Bigint,Indexoutofboundsexception,我试图从BigInteger类实现我自己版本的add()方法。到目前为止,当给定两个长度相同的数字时,它可以完美地工作,但当给定两个长度不同的数字时,它无法编译(索引超出范围)。解决这个问题的最好办法是什么 如果有帮助,两个值相加时的输出是10,1是20 public BigInt add(BigInt b) { int[] ans = new int[value.length]; int carry=0; if(this.lessTha
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;
}
如果我正确理解您的代码,
ans
长度需要比两个BigInt
长度中的较大者大一个。您的ans
仅与调用该方法的对象一样大。我会尝试以下方法:
public BigInt add2( BigInt b )
{
int answerLength = Math.max( b.value.length, this.value.length ) + 1;
int[] answer = new int[ answerLength ];
BigInt bigger = this;
BigInt smaller = b;
if( this.lessThan( b ) )
{
bigger = b;
smaller = this;
}
// copy the bigger value into answer
for( int i = bigger.value.length - 1; i >= 0; i-- )
{
answer[ i + 1 ] = bigger.value[ i ];
}
// add the smaller into the answer
int carry = 0;
int lengthOffset = answerLength - smaller.value.length;
for( int i = smaller.value.length - 1; i >= 0; i-- )
{
int result = answer[ i + lengthOffset ] + smaller.value[ i ] + carry;
carry = result / 10;
result %= 10;
answer[ i ] = result;
}
answer[ 0 ] = carry;
String ANSsz = convertArrayToString( answer );
BigInt Sum = new BigInt( ANSsz );
return Sum;
}
这真是一个非常奇怪的解决方案。首先,它有一个明显的溢出问题(两个整数相加的结果可能不适合一个整数本身),我不知道为什么我们想要用10除2个数的简单相加-这实际上只是将一个数转换为十进制字符串所必需的 不管怎样,只要想想两个数字的乘积可以有多少位数。为了简单起见,我们在base10中尝试了这一点,但概括起来很明显:
一个k位长的数字最多为
10^k-1
large。因此,如果我们有一个n位数的数字和一个m位数的数字,结果最多是:10^n-1+10^m-1=10^n+10^m-2
。我们能得到的最大值是,如果n==m,这相当于10^n*2-2,它明显小于10^(n+1)。这意味着该数字最多比两个数字中的较大者多一位(这也适用于基数2)。尝试填充数字,使其长度相同。我将以用于存储32位无符号值的int[]
为基础。这将是更有效的esp,因为整个目的是存储大量的数字。如果解决方案大于两个相加的值,则可能会出现问题。(ans可以是value.length+1长度)