#define max(a, b) ((a) > (b) ? (a) : (b))
static char* reverse(char *str)
{
char *l, *r, c;
for (l = str, r = str + strlen(str) - ; l < r; l++, r--) {
c = *l;
*l = *r;
*r = c;
}
return str;
}
/*
* Return the result of a big int as string when succeeded; otherwise
* a NULL is returned. The caller needs to take care of the returned
* heap memory; caller needs to ensure the inputs are valid big int.
*/
char* addBigInt(char *i1, char *i2)
{
char *p1, *p2, *p3, *res;
int len1, len2, val, carry;
if (!i1 || !*i1)
return strdup(i2);
if (!i2 || !*i2)
return strdup(i1);
len1 = strlen(i1);
len2 = strlen(i2);
if ((res = (char*)malloc(max(len1, len2) + )) == NULL)
return NULL;
for (p1 = i1 + len1 - , p2 = i2 + len2 - , p3 = res, val = ;
p1 != i1 - || p2 != i2 - || val;
*p3++ = val % + '', val /= ) {
if (p1 != i1 - )
val += *(p1--) - '';
if (p2 != i2 - )
val += *(p2--) - '';
}
*p3 = '\0';
return reverse(res);
}