Working Java code


  • 0
    X
    `public class Solution {
        public int evalRPN(String[] tokens) {
            Stack<String> stack = new Stack<String>();
            for(String token : tokens)
            {
                if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"))
                {
                    stack.push(evaluate(token, stack.pop(), stack.pop()));
                }
                else
                {
                    stack.push(token);
                }
            }
            
            return Integer.valueOf(stack.pop());
        }
        
        public String evaluate(String operator, String right, String left) {
            if(operator.equals("+"))
                return (Integer.valueOf(left) + Integer.valueOf(right)) + "";
            if(operator.equals("-"))
                return (Integer.valueOf(left) - Integer.valueOf(right)) + "";
            if(operator.equals("*"))
                return (Integer.valueOf(left) * Integer.valueOf(right)) + "";
            if(operator.equals("/"))
                return (Integer.valueOf(left) / Integer.valueOf(right)) + "";
                
            return "";
        }
    }`

Log in to reply
 

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