简体   繁体   中英

Using a list for BigInteger addition

I am implementing my own BigInteger class using an ArrayList and am unsure how to write my addition method.

public BigInt plus(BigInt operand){
    //deep copy?
    ArrayList<Byte> a = this.digit;
    ArrayList<Byte> b = operand.digit;
    ArrayList<Byte> sum = new ArrayList<>();

    //code  

    return new BigInt();
}

The goal is to pass in another BigInt, take its Arraylist of bytes and add it to the Arraylist of bytes of the current BigInt, but when doing this, if the value of adding 2 bytes together you would carry the '1' and add it to the next byte in the list.

IE:

BigInt1 = "3,2,1,7"

BigInt2 = "1,4,3,5"

Adding 7 and 5 would create 12, so the 1 is carried and 2 will be in that index for the returned BigInt.

The final BigInt should be

BigIntSum = "4,6,5,2"

My question is, how can I iterate through these lists, add the bytes and carry a number if necessary, and add that? Any help is greatly appreciated. BigInt has a constructor that can take a string that is turned into its own ArrayList

something like this...

carry = 0
for i = bigInt1.Length - 1 to zero
 sum = bigInt1[i] + bigInt2[i] + carry
 if (sum > 10) {
    sum = sum mod 10
    carry = 1
 else
    carry = 0
 endif
 bigIntResult = sum
loop i
// after the loop, if carry == 1, then you have overflow and you need to lengthen bigIntResult

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM