您的位置:首页 > 编程语言 > Go语言

POJ 1503(高精度整数加法) 解题报告

2011-03-18 00:15 295 查看
/*_____________________________________POJ 1503题_________________________________________________
Integer Inquiry
Time Limit: 1000MS  Memory Limit: 10000K
Total Submissions: 18770  Accepted: 7384

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
_________________________________________________________________________________________________*/
#include<stdio.h>
#include<string.h>

void Convert(char p[],int n)  //翻转
{
char temp;
int i,j;
for(i=0,j=strlen(p)-1; i<j; i++,j--)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}

int main()
{
int i,j,k,carry,remain;
char a[110]={'/0'}, b[110]={'/0'}, sum[110]={'/0'};  //由于相加后可能超过100位所以长度设为110位
//FILE *fin=fopen("input.txt","r");
//fscanf(fin,"%s",a);
scanf("%s",a);
Convert(a,strlen(a));  //将a[]翻转为从低位到高位存储
//fscanf(fin,"%s",b);
scanf("%s",b);
while(!(strcmp(b,"0")==0))  //输入未结束
{
Convert(b,strlen(b));  //将b[]翻转为从低位到高位存储
for(carry=0,k=0,i=0,j=0; i<strlen(a)&&j<strlen(b); i++,j++)
{
remain=(a[i]-'0'+b[j]-'0'+carry)%10;   //余数
carry=(a[i]-'0'+b[j]-'0'+carry)/10;    //进位,为0或1
sum[k++]=remain+'0';  //和sum[]也是从低位到高位存放
}
while(i<strlen(a))  //串a[]的位数多
{
remain=(a[i]-'0'+carry)%10;
carry=(a[i]-'0'+carry)/10;
sum[k++]=remain+'0';
i++;
}
while(j<strlen(b))  //串b[]的位数多
{
remain=(b[j]-'0'+carry)%10;
carry=(b[j]-'0'+carry)/10;
sum[k++]=remain+'0';
j++;
}
if(carry)  //a[],b[]的位数相同,但最高位还有进位,但加法的进位只可能是一位
sum[k++]=carry+'0';
for(i=0;i<110;i++)  //将a[],b[]清空
a[i]=b[i]='/0';
strcpy(a,sum);  //将sum[]拷贝给a[],做下一次加法的一个加数
//fscanf(fin,"%s",b);  //b[]是另一个加数
scanf("%s",b);
}
Convert(sum,strlen(sum));
printf("%s/n",sum);

return 0;
}

/******************************************************************************************
第一次没考虑到的情况:
(1)a,b位数同时用尽时可能还有剩的进位carry,导致9+9结果为8
(2)99+9的情况,a的位数用尽后还有进位carry,总之就是没考虑最高位进位
所以应该加上if(carry) {sum[k++]=carry+'0';}
******************************************************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息