# 150. Evaluate Reverse Polish Notation

67人阅读 评论(0)

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();
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：34750次
• 积分：2603
• 等级：
• 排名：第14013名
• 原创：241篇
• 转载：4篇
• 译文：0篇
• 评论：0条