题目描述
根据逆波兰表示法,求表达式的值。
运行示例
输入: [“2”, “1”, “+”, “3”, “*”]
输出: 9
解释: ((2 + 1) * 3) = 9
输入: [“4”, “13”, “5”, “/”, “+”]
输出: 6
解释: (4 + (13 / 5)) = 6
大体思路
- 建立栈,并依次将数字(非运算符)放入栈中
- 当遇到运算符时,将栈顶元素取出并删除两次,并把两数按顺序运算的结果放入栈中
- 最终栈中只有一个数字为栈顶元素,将其取出。
代码实现
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for(auto x:tokens)
{
if(x != "+" && x != "-" && x != "*" && x != "/")
stk.push(stoi(x));
else
{
int a = stk.top();
stk.pop();
int b = stk.top();
stk.pop();
if(x == "+")
{
int c = b + a;
stk.push(c);
}
if(x == "-")
{
int c = b - a;
stk.push(c);
}
if(x == "*")
{
int c = b * a;
stk .push(c);
}
if(x == "/")
{
int c = b / a;
stk.push(c);
}
}
}
return stk.top();
}
};