Evaluate Reverse Polish Notation
int evalRPN(vector<string>& tokens) {
stack<int> s;
int a,b;
for(auto t : tokens){
if(isOperator(t)){
b=s.top();
s.pop();
a=s.top();//ab顺序反了!!
s.pop();
switch (t[0]){//必须是char
case '+':
a+=b;
break;
case '-':
a-=b;
break;
case '*':
a*=b;
break;
case '/':
a/=b;
break;
}
s.push(a);
}
else{
s.push(stoi(t));
}
}
return s.top();
}
bool isOperator(const string &o){
return o.size()==1&&string("+-*/").find(o)!=string::npos;
}
Last updated
Was this helpful?