您的位置:首页 > 其它

HDU 1047 大数相加

2014-11-09 22:28 246 查看
题意:

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.

This problem contains multiple test cases!

The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between
input blocks.

The output format consists of N output blocks. There is a blank line between output blocks.

题目分析:因为本题要求的大数超出long long型的范围,因此常规方法无法解决越界的问题。但以字符串的形式读入后再一个个存进一个数组里再模拟加法的求和与进位就可以解决。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
int b[10001];
char a[10001];
void add(char *a)
{
int len=strlen(a);
int m=1;
int i;
for( i=len-1;i>=0;i--)
{
b[m]+=(a[i]-'0');//字符转数组
b[m+1]+=b[m]/10;//遇到进位则上一位加1
b[m]=b[m]%10;
m++;
}
}
int main()
{
int n,t,i;
scanf("%d",&n);
while(n--)
{
memset(b,0,sizeof(b));//初始化模和数组
while(scanf("%s",a)&&a[0]!='0')
add(a);
t=0;
for(i=10000;i>1;i--)
{
if(t==0&&b[i]==0)
continue;
else
{
t=1;
printf("%d",b[i]);
}
}
printf("%d\n",b[1]);
if(n!=0)
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: