题目:给定一个后缀序列,要求求值,只有加减;
输入:
123++4-
输出:
2
分析:读入字符串,然后遍历字符串,如果遇到数字就直接入栈,如果是加号或者减号,就栈顶两个元素出栈,并且把计算结果压入栈中。
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main() {
string a;
stack<int> stk;
cin >> a;
int L = a.length();
for (int i = 0; i < L; i++) {
if (a[i] == '+' || a[i] == '-') {
int b, c;
b = stk.top();
stk.pop();
c = stk.top();
stk.pop();
c = a[i] == '+' ? c + b : c - b;
stk.push(c);
}
else
stk.push(a[i]-'0');
}
printf("%d", stk.top());
return 0;
}