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 发布
本文介绍了一个使用C++实现的逆波兰表达式求值算法。该算法通过栈来处理加减乘除运算符,实现了对给定字符串列表中逆波兰表达式的计算。此方法适用于解析和计算不含括号的算术表达式。
310

被折叠的 条评论
为什么被折叠?



