1018: A+B again
-
题目描述:
谷学长有一个非常简单的问题给你,给你两个整数A和B,你的任务是计算A+B。
-
输入:
输入的第一行包含一个整数T(T<=20)表示测试实例的个数,然后2*T行,分别表示A和B两个正整数。注意整数非常大,那意味着你不能用32位整数来处理。你可以确定的是整数的长度不超过1000。
-
输出:
对于每一个样例,你应该输出两行,第一行是"Case #:",#表示第几个样例,第二行是一个等式"A+B=Sum",Sum表示A+B的结果。注意等式中有空格。
-
样例输入
2
1
2
112233445566778899
998877665544332211
-
样例输出
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
#include<iostream>
#include <stack>
#include <stdlib.h>
#include <stack>
#include <cstring>
using namespace std;
int main()
{
stack <int> n1;
stack <int> n2;
stack <int> sum;
string str1,str2;
char c1;
char c2;
int T;
cin>>T;
int carryTrans = 0;
for (int i = 0; i < T; ++i) {
cin >> str1;
cin >> str2;
if (str1.length() != str2.length()) { //如果长度不一致,首先进行等长处理
if (str1.length() > str2.length()) {
int temp1 = str1.length() - str2.length();
for (int j = 0; j < temp1; ++j) {
char temp = '0';
int atoi(temp);
n2.push(temp - 48);
}
} else {
int temp2 = str2.length() - str1.length();
for (int j = 0; j < temp2; ++j) {
char temp = '0';
int atoi(temp);
n1.push(temp - 48);
}
}
}
for (int j1 = 0; j1 < str1.length(); ++j1) {
char temp = str1[j1];
int atoi(temp);
n1.push(temp - 48);
}
for (int j2 = 0; j2 < str2.length(); ++j2) {
char temp = str2[j2];
int atoi(temp);
n2.push(temp - 48);
}
int T2;
if (str1.length() > str2.length()) {
T2 = str1.length();
} else {
T2 = str2.length();
}
for (int k = 0; k < T2; k++) {
int temp = n1.top() + n2.top() + carryTrans;
if (temp >= 10) {
temp = temp - 10;
carryTrans = 1;
}
else{
carryTrans = 0;
}
sum.push(temp);
n1.pop();
n2.pop();
}
if (carryTrans == 1){
sum.push(1);
}
cout<<"Case "<<i+1<<":"<<endl;
cout<<str1<<" + ";
cout<<str2<<" = ";
while (!sum.empty()) {
cout << sum.top();
sum.pop();
}
cout << endl;
}
return 0;
}
用了栈来储存数据,比起char数组可以按照数据的产犊来分配内存,而且之后的相加、输出都比较方便。