#include <stdio.h> #include <stdlib.h> #include <string.h> // 计算两个数之和 char* solve(char* s, char* t ) { int lens = strlen(s); int lent = strlen(t); // 保证lens是比较长的 if (lens < lent) { char* tmp = s; s = t; t = tmp; int temp = lens; lens = lent; lent = temp; } // 结果字符串最大可能长度是较长输入字符串长度加1(考虑进位) char* a = (char*)malloc((lens + 1) * sizeof(char)); if (a == NULL) { printf("内存分配失败\n"); return NULL; } int lena = 0; // 用于记录结果字符串a当前存储的位置索引,从开头往后存储,初始为0 int carry = 0; int i = lens - 1; // s字符串从末尾往前的索引 int j = lent - 1; // t字符串从末尾往前的索引 while (j >= 0) { int sum = (s[i] - '0') + (t[j] - '0') + carry; carry = sum / 10; a[lena++] = sum % 10 + '0'; i--; j--; } while (i >= 0) { int sum = (s[i] - '0') + carry; carry = sum / 10; a[lena++] = sum % 10 + '0'; i--; } if (carry > 0) { a[lena++] = carry + '0'; } a[lena] = '\0'; // 添加字符串结束符 // 反转结果字符串a,使其顺序正确 int left = 0; int right = lena - 1; while (left < right) { char temp = a[left]; a[left] = a[right]; a[right] = temp; left++; right--; } return a; }