Evaluate Reverse Polish Notation
Total Accepted: 11628 Total Submissions: 59786My Submissions
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:
bool valid_operator(const string token){
return(token.compare("+") == 0
|| token.compare("-") == 0
|| token.compare("*") == 0
|| token.compare("/") == 0);
}
int evalRPN(vector<string> &tokens) {
stack<int> stack_number;
vector<string>::iterator iter = tokens.begin();
while(iter != tokens.end()){
string token = *iter;
if(valid_operator(token)){
assert(stack_number.size() > 1);
int a, b;
b=stack_number.top();
stack_number.pop();
a=stack_number.top();
stack_number.pop();
switch(token[0]){
case '+':
a=a+b;
stack_number.push(a);
break;
case '-':
a=a-b;
stack_number.push(a);
break;
case '*':
a=a*b;
stack_number.push(a);
break;
case '/':
assert(b != 0);
a=a/b;
stack_number.push(a);
break;
}
}else {
stack_number.push(atoi(token.c_str()));
}
iter++;
}
assert(stack_number.size() == 1);
return stack_number.top();
}
};