1032: A + B Problem II
題目描述
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
輸入
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.
輸出
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 in the equation. Output a blank line between two adjacent test cases.
樣例輸入
4
1 2
112233445566778899 998877665544332211
998 2
4568 0012
樣例輸出
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
Case 3:
998 + 2 = 1000
Case 4:
4568 + 0012 = 4580
解題代碼
問題分析:簡單大數加法問題,但是這個題目裏面有一個坑,就是開頭爲0這種情況,解決方法也很簡單,開頭就是0的話,不入棧。
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
/**
* 大數加法 written by Smileyan
* 需要注意字符串開頭的0這個問題
*/
stack<int> BigNumAdd(char *str1,char *str2)
{
int i;
stack<int> stack1,stack2;
stack<int> result;
// 專門用來解決開頭的 0
i=0;
while(str1[i] == '0') i++;
for(; str1[i] != '\0'; i++)
{
stack1.push(str1[i]-'0');
}
i=0;
while(str2[i] == '0') i++;
for(; str2[i] != '\0'; i++)
{
stack2.push(str2[i]-'0');
}
// 用來記錄是否需要進位
bool flag=false;
while(stack1.empty()==false || stack2.empty() == false || flag)
{
int x1 = 0;
if(stack1.empty()==false)
{
x1 = stack1.top();
stack1.pop();
}
int x2 = 0;
if(stack2.empty()==false)
{
x2 = stack2.top();
stack2.pop();
}
// 如果兩個都爲空,則就是 0+0+進位
int r = x1+x2+flag;
if(r >= 10)
{
r -= 10;
flag = true;
}
else
{
flag = false;
}
result.push(r);
}
return result;
}
// written by Smileyan 多謝關注
int main()
{
char str1[250],str2[250];
int n;
stack<int> result;
int i;
cin>>n;
for(i=1; i<=n; i++)
{
cin>>str1>>str2;
result = BigNumAdd(str1,str2);
cout<<"Case "<<i<<":"<<endl;
cout<<str1<<" + "<<str2<<" = ";
while(result.empty()==false)
{
int num=result.top();
result.pop();
cout<<num;
}
cout<<endl<<endl;
}
return 0;
}
總結
和大數減法 差不多,唯一的區別就是題目中添加了開頭就是0這種 現實生活中不可能出現的情況。
Smileyan
2019年9月21日 10:16