A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 545685 Accepted Submission(s): 104216
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
思路:
输入两个字符串
假设刚开始为45678和234
左对齐:
45678
234
直接进行字符串逐位相加 是不行的(当字符串长度不同时)
那么将两个字符串反转,对齐:
87654
432
这样,每一位就对齐了
将较短的字符串的每一位加到较长的字符串的对应位,再减去一个’0’(ASCII)
87654 加上432后变成了 ‘12’‘10’‘8’‘5’‘4’ (’'内表示那个字符减去‘0’表示的十进制数)
再遍历一遍较长的字符串,如果当前位大于9 就减去10,那么相应的,高位加上1
还有一种情况:最高位大于10
那么需要追加一个1
最后将字符串再反转返回就可以了
AC代码:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string Add(string a,string b)//作为返回结果
{
if(a.size()<b.size()) swap(a,b); //将a作为较长的
reverse(a.begin(),a.end()); //反转a
reverse(b.begin(),b.end()); //反转b
for(int i=0;i<b.size();i++) //将b的每个字符对应的加到a上
a[i]+=(b[i]-'0');
for(int i=0;i<a.size()-1;i++) //开始进位
{
if(a[i]>'9')
{
a[i]-=10;
a[i+1]+=1;//高位加1
}
}
if(a[a.size()-1]>'9') //判断最高位是否大于10 如果大于 则追加高位为1
{
a[a.size()-1]-=10;
a.append("1");
}
reverse(a.begin(),a.end());//反转
return a; //返回
}
int main()
{
string a,b;
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
if(i>1)
cout<<endl;
cin>>a>>b;
cout<<"Case "<<i<<":\n";
cout<<a<<" + "<<b<<" = "<<Add(a,b)<<endl;
}
}