Evaluate Reverse Polish Notation(逆波蘭表達式)

Evaluate the value of an arithmetic expression in Reverse Polish Notation.git

Valid operators are +-*/. Each operand may be an integer or another expression.express

Some examples:lua

 ["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 };
相關文章
相關標籤/搜索