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
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> myStack;
vector<string>::iterator iter = tokens.begin();
for (; iter != tokens.end(); iter++) {
if (*iter != "+" && *iter != "-" && *iter != "*" && *iter != "/") {
int iot = atoi((*iter).c_str());
myStack.push(iot);
} else{
int ia, ib;
ib = myStack.top();
myStack.pop();
ia = myStack.top();
myStack.pop();
if (*iter == "+") {
ia += ib;
myStack.push(ia);
}
else if (*iter == "-") {
ia -= ib;
myStack.push(ia);
}
else if (*iter == "*") {
ia *= ib;
myStack.push(ia);
}
else if (*iter == "/") {
ia /= ib;
myStack.push(ia);
}
}
}
return myStack.top();
}
};