#define max(a, b) ((a) > (b) ? (a) : (b)) static char* reverse(char *str) { char *l, *r, c; for (l = str, r = str + strlen(str) - 1; 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) + 2)) == NULL) return NULL; for (p1 = i1 + len1 - 1, p2 = i2 + len2 - 1, p3 = res, val = 0; p1 != i1 - 1 || p2 != i2 - 1 || val; *p3++ = val % 10 + ‘0‘, val /= 10) { if (p1 != i1 - 1) val += *(p1--) - ‘0‘; if (p2 != i2 - 1) val += *(p2--) - ‘0‘; } *p3 = ‘\0‘; return reverse(res); }
时间: 2024-10-16 04:40:27