My Accepted Java solution


  • 0
    K

    public int evalRPN(String[] tokens)
    {
    Stack<String> stack = new Stack<String>();

        for (int i = 0; i < tokens.length; i++)
        {
            if (tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/"))
            {
                int firstVal = Integer.parseInt(stack.pop());
                int secondVal = Integer.parseInt(stack.pop());
                
                if (tokens[i].equals("+"))
                {
                    stack.push(String.valueOf(firstVal + secondVal));
                }
                else if (tokens[i].equals("-"))
                {
                    stack.push(String.valueOf(secondVal - firstVal));
                }
                else if (tokens[i].equals("*"))
                {
                    stack.push(String.valueOf(firstVal * secondVal));
                }
                else
                {
                    stack.push(String.valueOf(secondVal / firstVal));
                }
            }
            else
            {
                stack.push(tokens[i]);
            }
        }
        
        return Integer.parseInt(stack.pop());
    }

Log in to reply
 

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