# [leetcode] Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are `+`, `-`, `*`, `/`. Each operand may be an integer or another expression.

Some examples:

```  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6```

tags: stack

```class Solution {
public:
stack<int> s;
int evalRPN(vector<string> &tokens) {
for(vector<string>::iterator it = tokens.begin(); it != tokens.end(); it++){
try{
int operand = stoi(*it);
s.push(operand);
}
catch(invalid_argument e){//operator
int operand2 = s.top();
s.pop();
int operand1 = s.top();
s.pop();
int thisRe;
if (*it == "+"){
thisRe = operand1 + operand2;
}
else if(*it == "-"){
thisRe = operand1 - operand2;
}
else if(*it == "*"){
thisRe = operand1 * operand2;
}
else{
thisRe = operand1 / operand2;
}
s.push(thisRe);
}
}
int re = s.top();
s.pop();
return re;
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.