Adding Integer arrays

Q: You have two integer arrays. Treat these arrays as if they were big numbers, with one digit in each slot. Perform addition on these two arrays and store the results in a new array.

A: Runs in O(maxlen(a,b)) time.

int *AddArrays(int a[], int alen, int b[], int blen){
   int maxLen = max(alen, blen);
   int *c = new int[maxLen + 1];
   int acur = alen - 1;
   int bcur = blen - 1;
   int ccur = maxLen;
   int carry = 0;

   while(ccur >= 0){
      int cur = carry;
      
      if(acur >= 0)
         cur += a[acur--];
      
      if(bcur >= 0)
         cur += b[bcur--];
      
      c[ccur--] = cur % 10;
      carry = cur/10;
   }
   return c;
}
Advertisements