A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 521994 Accepted Submission(s): 99845
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
题目大意为计算给定两数之和,并按照格式输出。(这个格式我找了好久才发现,可能也是自己看题目不认真,很多杭电OJ题目都是这格式)
格式:就是Case #之间要有两行空格,但是最后一个Case输出后,只输出一个换行。
大概就是这样,算法的话是模拟加法计算,就像是我们平常做加法一样,通过加数、被加数以及进位的和来确定每一位的数字。要注意的是,计算完成后进位是否为0(我这里定义为carry),不是0的话就继续进位。
AC代码如下(C++代码):
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
for(int i=1;i<=n;i++)
{
string a,b,res;
cin>>a>>b;
string c=a,d=b; //输出原先的字符串
reverse(a.begin(),a.end());//反转字符串
reverse(b.begin(),b.end());
int alen=a.length(),blen=b.length();
if(alen<blen) a.append(blen-alen,'0');
else b.append(alen-blen,'0'); //使两字符串长度一致,便于加法计算,长度不足的以0补足
int carry=0,j=0;
for(int i=0;i<a.length();i++) //模拟加法
{
int tmp=a[i]-'0'+b[i]-'0'+carry;
res+=to_string(tmp%10);
carry=tmp/10;
}
while(carry){
res+=to_string(carry%10);
carry/=10;
}
reverse(res.begin(),res.end()); //原先是个位在前,故反转
for(int i=0;i<res.length();i++)
{
if(res[i]!='0') break;
j++;
} //判断最高位前有多少个0,然后舍弃输出
printf("Case %d:\n",i);
cout<<c<<" + "<<d<<" = ";
for(int k=j;k<res.length();k++)
{
cout<<res[k];
}
if(i!=n)cout<<"\n"<<"\n"; //输出格式
else cout<<"\n";
}
}
return 0;
}