## 操纵大数字作为字符串内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (21)

``````addBigNumbers(char *a1, char *a2, char *res)
``````

a1a2将包含我想要添加的2个大数字，res将包含这些数字序列的总和。我们希望我们创建的函数检查字符串是否仅包含数字。

``````#include <stdio.h>
#include <stdlib.h>
#define N 1000

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int addHugeNumbers(char *a1, char *a2, char *res){
int y=0, u=0, h=0;
res=strcat(a1,a2);
if(strlen(a1)>strlen(a2)){
y=atoi(a1);
u=atoi(a2);
h=y+u;
}
else{
y=atoi(a1);
u=atoi(a2);
h=u+y;
}
printf("%d", h);
}

int main(int argc, char *argv[]) {
char res[N];
char a1[N/2];
char a2[N/2];
scanf("%s", &a1);
scanf("%s", &a2);

return 0;
}
``````

### 1 个回答

char * strcat（char * dest，const char * src） 将src指向的以null结尾的字节字符串的副本附加到dest指向的以null结尾的字节字符串的末尾。字符src [0]替换dest末尾的空终止符。生成的字节字符串以空值终止。

``````#define N 1000

int addHugeNumbers(char *a1, char *a2, char *res){

char resultBuffer[N];
int i1 = (int)strlen(a1);
int i2 = (int)strlen(a2);
int carryOver = 0;
int ri = 0;
while (i1 > 0 || i2 > 0) {  // until both inputs have been read to their beginning
i1--;
i2--;

// read single digits and consider that a string might have already
// been read to its beginning
int d1 = i1 >= 0 ? a1[i1] - '0' : 0;
int d2 = i2 >= 0 ? a2[i2] - '0' : 0;

// check for invalid input
if (d1 < 0 || d1 > 9 || d2 < 0 || d2 > 9) {
return 0;
}

// calculate result digit, taking previous carryOver into account
int digitSum = d1 + d2 + carryOver;
carryOver = digitSum / 10;
digitSum %= 10;

resultBuffer[ri++] = digitSum + '0';
}
// write the last carryOver, if any
if (carryOver > 0) {
resultBuffer[ri++] = carryOver + '0';
}

// copy resultBuffer into res in reverse order:
while(ri--) {
*res++ = resultBuffer[ri];
}
// terminate res-string
*res = '\0';

return 1;
}

int main(int argc, char *argv[]) {
char res[N];
char a1[N/2] = "123412341234";
char a2[N/2] = "1231";