[Java] 10 lines concise solution


  • 0
    public int evalRPN(String[] tokens) {
            Deque<Integer> nums = new ArrayDeque<>();
            
            for (String s : tokens) {
                if (s.equals("+"))       nums.push(nums.pop() + nums.pop());
                else if (s.equals("-"))  nums.push(- nums.pop() + nums.pop());
                else if (s.equals("*"))  nums.push(nums.pop() * nums.pop());
                else if (s.equals("/")) {
                    int b = nums.pop(), a = nums.pop();
                    nums.push(a/b);
                } else  nums.push(Integer.valueOf(s));
            }
            
            return nums.pop();
        }
    

Log in to reply
 

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