Leetcode---Evaluate Reverse Polish Notation

xiaoxiao2021-02-28  14

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

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

import java.util.Stack; public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<Integer>(); for(String t : tokens){ switch(t){ case"+": stack.push(stack.pop()+stack.pop()); break; case"-": stack.push(-stack.pop()+stack.pop()); break; case"*": stack.push(stack.pop()*stack.pop()); break; case"/": int num1 = stack.pop(); int num2 = stack.pop(); stack.push(num2/num1); break; default: stack.push(Integer.parseInt(t)); } } return stack.pop(); } }
转载请注明原文地址: https://www.6miu.com/read-2600045.html