Easy and fast java solution


  • 0
    S
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<>();
            int n = tokens.length, i, first, second;
            
            for (i=0;i<n;i++) {
                switch (tokens[i]) {
                    case "+":
                        stack.push(stack.pop() + stack.pop());
                        break;
                    case "-":
                        first = stack.pop();second = stack.pop();
                        stack.push(second - first);
                        break;
                    case "*":
                        stack.push(stack.pop() * stack.pop());
                        break;
                    case "/":
                        first = stack.pop();second = stack.pop();
                        stack.push(second / first);
                        break;
                    default:
                        stack.push(Integer.parseInt(tokens[i]));
                }
            }
            return stack.pop();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.