# 150. 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

class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> mystack;
for (int i = 0; i < tokens.size(); i++){
string s = tokens[i];
if (s.compare("+") == 0){
int a = mystack.top();
mystack.pop();
int b = mystack.top();
mystack.pop();
mystack.push(a + b);
continue;
}
if (s.compare("-") == 0){
int a = mystack.top();
mystack.pop();
int b = mystack.top();
mystack.pop();
mystack.push(b - a);
continue;
}
if (s.compare("*") == 0){
int a = mystack.top();
mystack.pop();
int b = mystack.top();
mystack.pop();
mystack.push(a * b);
continue;
}
if (s.compare("/") == 0){
int a = mystack.top();
mystack.pop();
int b = mystack.top();
mystack.pop();
mystack.push(b / a);
continue;
}
mystack.push(atoi(s.c_str()));
}
return mystack.top();
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：150. Evaluate Reverse Polish Notation 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)