您的位置:首页 > 其它

杭电 1002题 A+B Problem II

2018-02-02 21:10 423 查看
Problem Description

I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.

Input

The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.

Output

For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line is the an equation “A + B = Sum”, Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.

Sample Input

2

1 2

112233445566778899 998877665544332211

Sample Output

Case 1:

1 + 2 = 3

Case 2:

112233445566778899 + 998877665544332211 = 1111111111111111110

代码

#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
#define M 40
#define N 1005

//该函数将两个字符串转换为整型数组并相加,最后输出
void sum(const char a[],const char b[]) {
int n1[1005],n2[1005];   //定义将字符串转换为的整型数组
int c[1005];             //存储结果值
int len1,len2,max;     //存储两个数组的长度以及二者的最大值
int g=0;    //存储进位,为0或者1
int temp;
len1=strlen(a);
len2=strlen(b);

//初始化两个数组
for(int i=0;i<1005;i++)
{
n1[i]=0;
n2[i]=0;
}

//将字符串转换为整型数组,利用ASCII的差值
for(int i=0;i<len1;i++)
{
n1[len1-1-i]=a[i]-'0';
}
for(int i=0;i<len2;i++)
{
n2[len2-1-i]=b[i]-'0';
}

max= len1>len2? len1:len2;

for(int i=0;i<max;i++)
{
temp=n1[i]+n2[i]+g;
g=(temp>=10? 1:0);
c[i]=temp%10;
}

if(g==1)
{
c[max]=1;
max++;
}

for(int i=max-1;i>=0;i--)
{
cout<<c[i];
}
cout<<endl;

}
int main () {
char str[M]
;
int T;
cin>>T;

for(int i=0;i<2*T;i=i+2)
{
cin>>str[i];
cin>>str[i+1];

cout<<"Case "<<(i/2+1)<<":"<<endl;
cout<<str[i]<<" + "<<str[i+1]<<" = ";
sum(str[i],str[i+1]);    //计算并输出结果
//判断最后一个换行是否输出(格式要求)
if((i/2+1)!=T)
{
cout<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: