0

我正在尝试从 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;
    }
4

3 回答 3

0

If I understand your code correctly, ans length needs to be one larger than the greater of the two BigInt lengths. Your ans is only ever as big as the object the method is being called on.

于 2012-02-18T03:58:48.577 回答
0

我会尝试这样的事情:

   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;
      }
于 2012-02-18T04:18:59.887 回答
0

这真的是一个非常奇怪的解决方案。首先,它有明显的溢出问题(两个添加的 int 的结果可能不适合 int 本身),我不知道为什么我们想要除以 10 来简单地添加 2 个数字 -这实际上只是将数字转换为十进制字符串所必需的。

无论如何,只需考虑两个数字的乘积可以有多少位数。为简单起见,我们在 base10 中尝试这样做,但概括很明显:

一个 k 位数的长数至多是10^k - 1大的。因此,如果我们有一个 n 位数字和一个 m 位数字,则结果最多为:10^n - 1 + 10^m - 1 = 10^n + 10^m - 2。我们可以得到的最大值是如果 n == m 相当于 10^n * 2 - 2 显然小于 10^(n+1)。这意味着该数字最多比两个数字中的较大数字多一个数字(这也适用于基数 2)。

于 2012-02-18T04:44:14.363 回答