class Solution {
public:
int evalRPN(vector<string> &tokens)
{
if(tokens.empty()) return 0;
stack<int> s;
for(size_t i=0;i!=tokens.size();i++)
{
if(tokens[i]!="+" && tokens[i]!="-"
&& tokens[i]!="*" && tokens[i]!="/")
{//不是 operator,转成int入栈
s.push(stoi(tokens[i]));
}
else
{//是operator,计算后入栈
int rhs=s.top();
s.pop();
int lhs=s.top();
s.pop();
int tmp=0;
if(tokens[i]=="+")
{
tmp=lhs+rhs;
}
if(tokens[i]=="-")
{
tmp=lhs-rhs;
}
if(tokens[i]=="*")
{
tmp=lhs*rhs;
}
if(tokens[i]=="/")
{
tmp=lhs/rhs;
}
s.push(tmp);
}
}
return s.top();
}
};
Evaluate Reverse Polish Notation
最新推荐文章于 2022-03-25 16:52:08 发布