After failing to answer an interview question, I went back home and coded the answer for my own improvement. The questions was: Given two arrays containing a number, but with each element of the array containing a digit of that number, calculate the sum and give it in the same format.There must be no leading zeros in the resulting array.
My main concern is that I am being redundant with my logic, or that my code is not clear.
int *sumOfTwo(int *a1,int *a2, int lengthOfA1, int lengthOfA2, int *lengthDest) {
//I assume there is error checking for null pointers, etc.
int *answer;
int maxSize, minSize, diff;
int a1IsLongest = TRUE;
if(lengthOfA1 > lengthOfA2) {
maxSize = lengthOfA1;
minSize = lengthOfA2;
a1IsLongest = TRUE;
}
else {
maxSize = lengthOfA2;
minSize = lengthOfA1;
a1IsLongest = FALSE;
}
diff = maxSize - minSize;
answer = malloc(maxSize * sizeof(int));
int i, extraTen, result;
extraTen = 0;
*lengthDest = maxSize;
//printf("This is lengthDest: %d\n", *lengthDest);
for (i = maxSize-1; i >= 0; i--) {
//add numbers, check if bigger than 10
//check if arrays are of different sizes we want to access
//the end from each, so need to account for this.
if(diff == 0) {
//arrays are equal in size
result = a1[i] + a2[i] + extraTen;
extraTen = 0;
}
else{
//arrays are different sizes
if(! ((i - diff) < 0)) {
if(a1IsLongest) {
result = a1[i] + a2[i - diff] + extraTen;
extraTen = 0;
}
else {
result = a1[i - diff] + a2[i] + extraTen;
extraTen = 0;
}
}
else {
if(a1IsLongest) {
result = a1[i] + extraTen;
extraTen = 0;
}
else {
result = a2[i] + extraTen;
extraTen = 0;
}
}
}
//the new malloc can only happen here
if (result >= 10) {
//check if at beginning of array
if(i == 0) {
maxSize = maxSize + 1;
*lengthDest = maxSize;
//printf("This is lengthDest: %d\n", *lengthDest);
//overflowing, need to realloc
int *temp = malloc(maxSize * sizeof (int));
int j;
//copy old elements into new array
for(j = 0; j < maxSize; j++) {
//printf("index: %d\n", j);
if(j == 0) {
temp[j] = 1;
}
else if(j == 1) {
temp[j] = result % 10;
}
else {
temp[j] = answer[j-1];
}
}
free(answer);
answer = temp;
return answer;
}
else{
//printf("in the else of the i equals 0.\n");
answer[i] = result % 10;
extraTen = 1;
}
}
else {
//printf(" results is less than 10\n");
answer[i] = result;
}
}
return answer;
}