10 line Java clean code using stack


  • 0
    M

    Assuming the input is alway valid.

        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<>();
            for (String s : tokens) {
                if ("+".equals(s)) stack.push(stack.pop() + stack.pop());
                else if ("-".equals(s)) stack.push(-stack.pop() + stack.pop());
                else if ("/".equals(s)) stack.push((int)(1D / stack.pop() * stack.pop()));
                else if ("*".equals(s)) stack.push(stack.pop() * stack.pop());
                else stack.push(Integer.valueOf(s));
            }
    
            return stack.pop();
        }
    

Log in to reply
 

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