A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 439087 Accepted Submission(s): 85433
原题链接
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
题解:题目要求求A+B的值,但是会很大,所以需要用数组存,说下我的思路,两个字符数分别存两串数,长的放在num1,短的放num2,翻转后计算,一位一位加,用一个变量(k2)来表示上一位的进位,如果进位就为1,未进位就为0,num1[i] + num2[i]+k2 的值如果转换成数值后大于等于10就进位,反之就不进位,依次计算就行了,需要注意的是中间num2的字符用完了,表示当前值的变量就从num1[i] + num2[i]+k2 变成num1[i]+k2。还有最后如果k2不为0的话那么就表示前面还有一位没有放进去需要单独放个1在前面。下面是AC代码:
#include"iostream"
#include"algorithm"
#include"string"
using namespace std;
int main()
{
int n,j=1;
cin >> n;
while(n--)
{
string num,num1,num2,num4,num5;//新数,数1,数2,数1备份,数2备份
cin >> num1 >> num2;
num4 = num1,num5=num2;
if(num1.length() < num2.length()) //长的放在num1
num1 = num5,num2 = num4;
reverse(num1.begin(),num1.end());//翻转字符串
reverse(num2.begin(),num2.end());
int i,k,k2=0;//下标,当前位的值,进位值
for(i=0;i<num1.length();i++)
{
if(i >= num2.length()) k = num1[i]-48 + k2;//num2用完就只用num1
else k = (num1[i]-48) + (num2[i]-48) + k2;
if(k <= 9)
{
num = (char)(k+48)+num;
k2 = 0;
}
else
{
num = (char)(k-10+48)+num;
k2 = 1;
}
}
if(k2) num = '1'+num;//如果最后还需要进位,则单独在前面放个1
cout << "Case " << j << ":" << endl;
cout << num4 << " + " << num5 << " = " << num << endl;
j++;
if(n-1 >= 0) cout << endl;//控制格式
}
return 0;
}