A - Integer Inquiry
Time Limit:1000MS Memory Limit:10000KB 64bit IO Format:%I64d & %I64u
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.)
``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.
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
高精度的加法运算:(一般所给的整数超过了int型、long long型)
先将整数以字符串的形式储存在一维数组中,再将数组翻转并转化为用整形数组储存,注意所给整数是否有前导0,然后对每一位进行累加,将所得的值直接储存在相应位,先不进行进位操作,等累加结束后,再做进位操作,最后要倒着从数组不为零的数输出即可(注意结果为0的特殊情况)。
代码如下:
#include<stdio.h>
#include<string.h>
//定义一维字符数组str[ ]临时储存输入的较大数
char str[105];
//一维整形数组sum[ ]储存每两个数相加是各个位上没有进位前的和
int sum[110];
//定义一个函数,用来将字符转换为整数,并求和
void switch_sum()
{
int i,j,n;
n=strlen(str)-1;
for(j=0,i=n;i>=0;i--,j++)
{
sum[j]=sum[j]+str[i]-'0';
}
}
int main()
{
int i,j,num;
//初始化数组sum[ ],使得各个位的和为零
memset(sum,0,sizeof(sum));
/*调用函数,求和;
注意:输入的数可能前导有零,不可以用语句
“str[0]!='0'”判断,应该用“strcmp(str,"0")!=0”判断*/
while(scanf("%s",str)&&strcmp(str,"0")!=0)
{
switch_sum();
}
//对求和之后的每一位进行操作,如果超过9,就要进位
for(i=0;i<110;i++)
{
if(sum[i]>9)
{
num=sum[i]/10;
sum[i]=sum[i]%10;
sum[i+1]=sum[i+1]+num;
}
}
//从数组sum右边开始第一个不为零的数就是最高位,记录下标
for(i=105;sum[i]==0;i--);
//从数组sum右端开始输出
for(j=i;j>=0;j--)
printf("%d",sum[j]);
printf("\n");
return 0;
}