- 使用双栈来实现。
- 关键是注意细节。
#include<iostream>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;
string solve(string s, string t) {
// write code here
stack<int> left_string;
stack<int> right_string;
stack<int> result;
string res = "";
int max_length = 0;
for(int i = 0; i< s.length();i++){
left_string.push(s[i]-'0');
}
for(int i = 0; i< t.length();i++){
right_string.push(t[i]-'0');
}
if(left_string.size()>=right_string.size()){
max_length = left_string.size();
}else{
max_length = right_string.size();
}
int add_on = 0;// 进位
while(max_length){
int up = 0; // 上面的数字
int down = 0;//下面的数字
if(!left_string.size()){
up = 0;
}else{
up = left_string.top();
left_string.pop();
}
if(!right_string.size()){
down = 0;
}else{
down = right_string.top();
right_string.pop();
}
int sum = up+down + add_on;
add_on = 0;
if(sum>=10){
result.push(sum-10) ;
add_on = 1;
if(max_length==1){//当最后一步最高位需要进位的时候。
result.push(1);
}
}else{
result.push(sum);
}
max_length--;
}
while(!result.empty()){
res+= result.top() + '0';
result.pop();
}
return res;
}
int main(){
string s,t;
while(cin>>s>>t){
string res;
res = solve(s,t);
cout<<res<<endl;
}
return 0;
}