题目来自洛谷
P1449 后缀表达式
题目描述
所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。
如:3*(5–2)+7
对应的后缀表达式为:3.5.2.-*7.+@
。’@’为表达式的结束符号。‘.’为操作数的结束符号。
输入格式
输入:后缀表达式
输出格式
输出:表达式的值
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
typedef long long LL;
string s;
stack<LL> stk;
int main()
{
cin >> s;
int t = 0;
for(int i = 0; i < s.size(); i ++)
{
if(s[i] == '*')
{
LL a = stk.top(); stk.pop();
LL b = stk.top(); stk.pop();
stk.push(b * a);
}
else if(s[i] == '+')
{
LL a = stk.top(); stk.pop();
LL b = stk.top(); stk.pop();
stk.push(b + a);
}
else if(s[i] == '-')
{
LL a = stk.top(); stk.pop();
LL b = stk.top(); stk.pop();
stk.push(b - a);
}
else if(s[i] == '/')
{
LL a = stk.top(); stk.pop();
LL b = stk.top(); stk.pop();
stk.push(b / a);
}
else if(s[i] == '.')
{
stk.push((LL)t);
t = 0;
}
else if(s[i] == '@')
{
break;
}
else if(s[i] >= '0' && s[i] <= '9')
{
t = t * 10 + (s[i] - '0');
}
}
cout << stk.top() << endl;
return 0;
}