Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators is+
,-
,*
,/
. Each operand is an integer or another expression.
Some Examples:
["2", "1", "+", "3", "*")--((2 + 1) (3)-9 ["4", "", "5", "/", "+"], 4 + (13/5))
It has been previously mentioned that the generation and operation of inverse Polish expressions is actually simpler to calculate. See Blog for details.
Package Com.liuhao.acm.leetcode;import java.util.arraydeque;import java.util.deque;/** * Calculate inverse Polish expression * * @author Liuhao * * Evaluate the value of an arithmetic expression in Reverse Polish * Notation. * * Valid operators is +,-, *,/. Each operand is an integer or * another expression. * * Some Examples: ["2", "1", "+", "3", "*"), 1 * ["3", "+", "9", "/", "+"]---((2 + 4) * 5).-> ; (4 + (13/5)), 6 * */public class EVALRPN {public static int evalrpn (string[] tokens) {//stack, used to iterate through the initial string array deque<int eger> stack = new arraydeque<integer> (), int A, b;//temporary stack pops two elements/** * iterates through the initial string array, * If the current character is an operator, two elements are popped from the stack, and the operator pairs They perform operations and then press the result of the operation into the stack * If the reading is a number, it is pressed directly into the stack, no other operation */for (int i = 0; i < tokens.length; i++) {String temp = Tokens[i];switch (temp) {case "+": A = Stack.pop (); b = Stack.pop (); Stack.push ((b + a)); Break;case "-": A = Stack.pop (); b = Stack.pop (); Stack.push (b) -a); Break;case "*": A = Stack.pop (); b = Stack.pop (); STACk.push (b * a); Break;case "/": A = Stack.pop (); b = Stack.pop (); if (a = = 0) {return-1;} Stack.push (b/a); Break;default:stack.push (Integer.parseint (temp));}} int result = Stack.peek (); return result;} public static void Main (string[] args) {string[] input = new string[] {"4", "13", "5", "/", "+"}; SYSTEM.OUT.PRINTLN (EVALRPN (input));}}
"Leetcode Brush problem Java Edition" Evaluate Reverse Polish Notation (calculation inverse Polish expression)