0

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;

    }
1
  • What language are you working in? Commented Oct 10, 2014 at 1:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.