问题描述:
给定一个后缀序列,要求求值,只有加减
样例输入:
输入:
123++4-
输出:
2
代码:
#include <cstdio>
#include <stack>
#include <cstring>
using namespace std;
const int maxn = 1010;
char str[maxn];
stack<int> number;
int main(){
scanf("%s", str);
int len = strlen(str);
for(int i = 0; i < len; i++){
if(str[i] >= '0' && str[i] <= '9'){
int num = str[i] - '0';
number.push(num);
}else if(str[i] == '+'){
int n1, n2;
if(!number.empty()){
n1 = number.top();
number.pop();
}
if(!number.empty()){
n2 = number.top();
number.pop();
}
number.push(n1 + n2);
}else if(str[i] == '-'){
int n1, n2;
if(!number.empty()){
n1 = number.top();
number.pop();
}
if(!number.empty()){
n2 = number.top();
number.pop();
}
number.push(n2 - n1);
}
}
printf("%d", number.top());
return 0;
}