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/* 2 * solution: 3 * using the auxiliary stack to calculate the inverse polish expression 4*1. traverses the array. The current string is in the stack when it is a number; 5*2. when the operator is used, two elements at the top of the stack are displayed to complete the calculation and the calculation result is written into the stack. 6*3. the traversal is complete. When the stack is not empty, the top element of the stack is returned and the calculation is complete. 7 */8 public class solution {9 Public int evalrpn (string [] tokens) {10 int factor1, factor2, result = 0; 11 stack <string> stack = new stack <string> (); 12 INT Len = tokens. length; 13 for (INT I = 0; I <Len; I ++) {14 if (tokens [I]. equals ("+") {15 factor1 = integer. parseint (stack. pop (); 16 factor2 = integer. parseint (stack. pop (); 17 result = factor1 + factor2; 18 stack. push (result + ""); 19 20} else if (Kens [I]. equals ("-") {21 factor1 = integer. parseint (stack. pop (); 22 factor2 = integer. parseint (stack. pop (); 23 result = factor2-factor1; 24 stack. push (result + ""); 25 26} else if (tokens [I]. equals ("*") {27 factor1 = integer. parseint (stack. pop (); 28 factor2 = integer. parseint (stack. pop (); 29 result = factor1 * factor2; 30 stack. push (result + ""); 31 32} else if (tokens [I]. equals ("/") {33 facto R1 = integer. parseint (stack. pop (); 34 factor2 = integer. parseint (stack. pop (); 35 result = factor2/factor1; 36 stack. push (result + ""); 37 38} else {39 stack. push (tokens [I]); 40} 41} 42 43 If (! Stack. isempty () 44 result = integer. parseint (stack. Pop (); 45 return result; 46} 47}
[Leetcode]-evaluate reverse Polish notation