150. 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
Subscribe to see which companies asked this question
Hide Similar Problems
public class Solution { public int evalRPN(String[] tokens) { if(tokens.length == 0) return 0; Deque<Integer> stack = new ArrayDeque<Integer>(); for(String str: tokens) { if(str.equals("+")) stack.push(stack.pop()+stack.pop()); else if(str.equals("-")) { int v1 = stack.pop(); int v2 = stack.pop(); stack.push(v2-v1); } else if(str.equals("/")) { int v1 = stack.pop(); int v2 = stack.pop(); stack.push(v2/v1); } else if(str.equals("*")) stack.push(stack.pop()*stack.pop()); else stack.push(Integer.parseInt(str)); } return stack.pop(); } }

浙公网安备 33010602011771号