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
Tags:
Stack;
This problem is a suffix expression. stack is the most simple and effective solution. When a number is encountered, it is pushed into the stack. When an operator number is encountered, two numbers are taken from the top of the stack for calculation. However, pay attention to one problem. The correct operation order of the two numbers displayed each time should be the number that pops up later, and the number that pops up first should be later. Example:
0 3/
In the pop-up window, 3 is popped up first, 0 is followed, and originally it is 0/3. If it is not in the correct order, it is changed to 3/0, and the program will crash due to a serious error!
I think this question is very simple, but it took a long time to complete the problem. Before programming, you must think more and start it!
Paste the code:
1 int istoken (string s) {2 if (s. compare ("+") = 0) 3 return 1; 4 if (s. compare ("-") = 0) 5 return 2; 6 if (s. compare ("*") = 0) 7 return 3; 8 if (s. compare ("/") = 0) 9 return 4; 10 return-1; 11} // different return values correspond to different situations 12 int transform (string s) {13 return atoi (s. c_str (); // Convert string to int14} 15 class Solution {16 public: 17 int evalRPN (vector <string> & tokens) {18 int len = tokens. size (); 19 int I; 20 stack <int> end; 21 for (I = 0; I <len; I ++) {22 if (istoken (tokens [I]) =-1) {// Press the number to stack 23 end. push (transform (tokens [I]); 24} 25 else {26 int n1 = end. top (); 27 end. pop (); 28 int n2 = end. top (); 29 end. pop (); // here n1 and n2 exchange the order 30 switch (istoken (tokens [I]) {31 case 1: {n1 + = n2; break ;} 32 case 2: {n1-= n2; break;} 33 case 3: {n1 * = n2; break;} 34 case 4: {n1/= n2; break ;} 35} 36 end. push (n1); 37} 38 39} 40 return end. top (); 41} 42 };
Evaluate Reverse Polish Notation (5)