描述
计算逆波兰式(后缀表达式)的值
运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式
思路:这道题直接给了后缀表达式,所以省去了我们将中序表达式转换为后缀表达式的过程。
后缀表达式的求值应借用栈来实现,即按顺序扫描后缀表达式,将数字入栈,遇到运算符,则弹出栈顶的两个元素进行相应运算,然后将运算结果再次入栈,重复此操作直到扫描结束。
代码:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
// write code here
stack<int> Oprite;
for(auto x : tokens)
{
if(x=="+" || x == "-" || x == "*" || x == "/")
{
if(Oprite.size()<2) return 0;
int a{Oprite.top()};
Oprite.pop();
int b{Oprite.top()};
Oprite.pop();
if(x == "+")
{
Oprite.push((int){a+b});
}
else if(x == "-")
{
Oprite.push((int){b-a});
}
else if(x == "*")
{
Oprite.push((int){a*b});
}
else if(x == "/")
{
if(a == 0) return 0;
Oprite.push((int){b/a});
}
}
else
{
Oprite.push(atoi(x.c_str())); //string 转换为 int类型 需要注意: atoi(x.c_str())
}
}
return Oprite.top();
}
};