简体   繁体   中英

How to add together an array representation of an integer with different number of digits?

How would I add together two integers with different number of digits, using an array, without causing an out of bounds exception?

For example: 500 + 99 each digit is an element of the array

This is how I'm doing it right now:

 int aIILength = infiniteInteger.length-1;
 int bIILength = anInfiniteInteger.infiniteInteger.length-1;
 for(int f = aIILength; f >0; f--){

        int aTempNum = infiniteInteger[f];


        int bTempNum = anInfiniteInteger.infiniteInteger[f];

        result = aTempNum + bTempNum;

        //array representation of sum
        tempArray[f] = result;

    }

Let the counter in the loop go from 1 and up, and use it to access the digits from the end of each array.

You need a carry to hold the overflow of adding each set of digits.

Loop until you run out of digits in both arrays, and carry is zero.

Check the range when you access the digits from the arrays, and use zero when you run out of digits.

int aIILength = infiniteInteger.length;
int bIILength = anInfiniteInteger.infiniteInteger.length;
int carry = 0;
for(int f = 1; f <= aIILength || f <= bIILength || carry > 0; f++){
  int aTempNum;
  if (f <= aIILength) {
    aTempNum = infiniteInteger[aIILength - f];
  } else {
    aTempNum = 0;
  }
  int bTempNum;
  if (f <= bIILength) {
    bTempNum = anInfiniteInteger.infiniteInteger[bIILength - f];
  } else {
    bTempNum = 0;
  }
  result = aTempNum + bTempNum + carry;
  tempArray[tempArray.length - f] = result % 10;
  carry = result / 10;
}

Note: Make tempArray longer than both the operand arrays, so that it has place for a potential carry to the next digit.

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