How to add two numbers of any length in java?

后端 未结 8 1158
广开言路
广开言路 2020-12-06 01:20

How to add two numbers of any length in java?

Say for example, in java long size is 64 bit. So the maximum range is -9223372036854775808 to 9223372036854775807. Am i

8条回答
  •  攒了一身酷
    2020-12-06 01:57

    Is there any big difference between the addition of two very large numbers using BigInteger and the method, i specified above (add each character from end and store remainder in temporary variable and goes on).

    The difference is that you could use a larger radix, for example. Suppose the radix is 10000, not just 10. When the code of my previous answer would be modified like this:

    int len1 = A[0],  len2 = B[0], divisor = 0;
    int len = len1 >= len2 ? len1 : len2;
    
    for (int i=1;i<=len;i++) {
      if (i>len1) C[i] = B[i]+divisor;
      else if (i>len2) C[i] = A[i]+divisor;
      else C[i] = A[i]+B[i]+divisor;
      divisor = C[i]/10000;
      C[i] %= 10000;
    }
    while (divisor>0) {
      C[++len] = divisor%10000;
      divisor /= 10000;
    }
    C[0] = len;
    

    In that case the code runs 4 time faster (since there is no difference for the virtual machine in arithmetic operations, since they depend on the constant only). Also, this means, that the array of integers will be 4 times smaller. The only problem this causes is how to format the output.

提交回复
热议问题