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
说明:逆波兰表达式又叫做后缀表达式。在通常的表达式中,二元运算符总是置于与之相关的两个运算对象之间,所以,这种表示法也称为中缀表示。
 1 class Solution {
 2 public:
 3 
 4     int evalRPN(vector<string> &tokens) {
 5         int a, b;
 6         stack<int> s;
 7         for(int i = 0; i < tokens.size(); i ++)
 8         {
 9             if(isdigit(tokens[i][0]) || tokens[i].length() > 1)
10             {
11                 s.push(atoi(tokens[i].c_str()));
12                 continue;
13             }
14             a = s.top();s.pop();
15             b = s.top();s.pop();
16             switch(tokens[i][0])
17             {
18                 case '+': s.push(b + a); break;
19                 case '-': s.push(b - a); break;
20                 case '*': s.push(b * a); break;
21                 case '/': s.push(b / a); break;
22             }
23         }
24         return s.top();
25     }
26 };
原文地址:https://www.cnblogs.com/meaworld/p/3897335.html