class Solution {
public:
int evalRPN(vector<string>& tokens)
{
if(tokens.empty())
return 0;
stack<int> s;
int res=0;
const int n=tokens.size();
for(int i=0;i<n;++i)
{
if(tokens[i]=="+")
{
int firstVal=s.top();
s.pop();
int secondVal=s.top();
s.pop();
res=secondVal+firstVal;
s.push(res);
}
else if(tokens[i]=="-")
{
int firstVal=s.top();
s.pop();
int secondVal=s.top();
s.pop();
res=secondVal-firstVal;
s.push(res);
}
else if(tokens[i]=="*")
{
int firstVal=s.top();
s.pop();
int secondVal=s.top();
s.pop();
res=secondVal*firstVal;
s.push(res);
}
else if(tokens[i]=="/")
{
int firstVal=s.top();
s.pop();
int secondVal=s.top();
s.pop();
res=secondVal/firstVal;
s.push(res);
}
else
{
int temp=atoi(tokens[i].c_str());
s.push(temp);
}
}
return s.top();
}
};
Evaluate Reverse Polish Notation
最新推荐文章于 2022-03-25 16:52:08 发布