用C语言求1234567890123456789+9876543210123456789,最好源代码有解释,万分感谢

2025-04-18 16:58:03
推荐回答(1个)
回答1:

#include
#include
#include
int main()
{
char a[1000][1002] = { 0 };
char result[1002] = { '0' };
int n, i, j;
scanf("%d", &n);
for (i = 0; i < n; ++i)
scanf("%s", a[i]);
for (i = 0; i < n; ++i)
{
int len1 = strlen(a[i]);
int len2 = strlen(result);
if (len1 < len2)
{
int temp = 0;
for (j = len2 - 1; j >= len2 - len1; --j)
{
if (temp + result[j] + a[i][len1 + j - len2] - '0' - '0' >= 10)
{
result[j] = temp + result[j] + a[i][len1 + j - len2] - '0' - 10;
temp = 1;
}
else
{
result[j] = temp + result[j] + a[i][len1 + j - len2] - '0';
temp = 0;
}
}
for (j = len2 - len1 - 1; j >= 1; --j)
{
if (result[j] + temp <= '9')
{
result[j] += temp;
temp = 0;
}
else
{
result[j] = '0';
temp = 1;
}
}
if (result[0] + temp <= '9')result[0] += temp;
else
{
result[0] = '0';
for (j = len2 - 1; j >= 0; --j)
result[j + 1] = result[j];
result[0] = '1';
}
}
else
{
int temp = 0;
char TEMP[1001] = { 0 };
for (j = len1 - 1; j >= len1 - len2; --j)
{
if (temp + a[i][j] + result[len2 + j - len1] - '0' - '0' >= 10)
{
TEMP[j] = temp + result[len2 + j - len1] + a[i][j] - '0' - 10;
temp = 1;
}
else
{
TEMP[j] = temp + result[len2 + j - len1] + a[i][j] - '0';
temp = 0;
}
}
for (j = len1 - len2 - 1; j >= 1; --j)
{
if (a[i][j] + temp <= '9')
{
TEMP[j] = temp + a[i][j];
temp = 0;
}
else
{
TEMP[j] = '0';
temp = 1;
}
}
if (len1 > len2)
{
if (a[i][0] + temp <= '9')TEMP[0] = temp + a[i][0];
else
{
TEMP[0] = '0';
for (j = len1 - 1; j >= 0; --j)
TEMP[j + 1] = TEMP[j];
TEMP[0] = '1';
}
}
else
{
if (temp == 1)
{
for (j = len1 - 1; j >= 0; --j)
TEMP[j + 1] = TEMP[j];
TEMP[0] = '1';
}
}
strcpy(result, TEMP);
}
}
int zero = 0;
while (result[zero] == '0')
{
++zero;
}
int length = strlen(result);
for (j = zero; j < length; ++j)
result[j - zero] = result[j];
length -= zero;
for (j = length; j < 1002; ++j)
result[j] = 0;
if (result[0] == 0)result[0] = '0';
printf("%s", result);
system("pause");
return 0;
}

以前做的一个,可以求多个大数的和。你这个问题就属于求大数的和。关键思路是字符串化,难点在于进位,用一个temp储存进位与否即可。