文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。
高精度加法
Description
One of the first users of BIT’s new supercomputer was Chip Diller. He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
“This supercomputer is great,” remarked Chip. “I only wish Timothy were here to see these results.” (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.)
Input
The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative).
The final input line will contain a single zero on a line by itself.
Output
Your program should output the sum of the VeryLongIntegers given in the input.
Sample Input
123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0
Sample Output
370370367037037036703703703670
Slyar:说下题意。给你至多100行超大整数,以0结束输入,要求你求出这些超大整数的和。
高精度加法运算,试了几种思路,感觉下面这种看起来最舒服…
例如19999 + 999 + 9,看图更清晰
1、以字符串格式读入超大整数,然后将每一位转换成整型并逆序存放在数组中。
2、把每次读入字符串的长度存放在0号元素中(sum[i][0])。
3、将所有大整数的和存放在0号字符串中(sum[0])。
4、从0号字符串最大处向前寻找第一个不为0的元素,然后逆序输出和。
#include
#include
#include
#define MAX 105
char sum[MAX][MAX];
char str[MAX];
int main()
{
int i, j, he, jin, line;
for(i = 0; ;i++)
{
gets(str);
if (str[0] == '0' && str[1] == 0) break;
/* 0号元素记录长度 */
sum[i][0] = strlen(str);
/* 逆序存放大整数 */
for (j = 1; j <= sum[i][0]; j++)
{
sum[i][j] = str[sum[i][0] - j] - '0';
}
}
/* 记录数据行数 */
line = i;
/* 用第0行存放和 */
for (i = 1; i < line; i++)
{
/* 进位标记归0 */
jin = 0;
/* 进行加法运算 */
for (j = 1; j < MAX - 1; j++)
{
he = sum[0][j] + sum[i][j] + jin;
/* 进位 */
jin = he / 10;
sum[0][j] = he % 10;
}
}
/* 从后向前找到不为0的第一个数 */
for(i = MAX - 1; sum[0][i] == 0; i--);
/* 输出和 */
for (; i >= 1; i--)
{
printf("%d", sum[0][i]);
}
printf("\n");
//system("pause");
return 0;
}