Accepted Java Solution


  • 2
    A

    Should include some error checking, but accepted none the less.

        public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack <>();
        for (int i=0; i < tokens.length; i++) {
            String token = tokens[i];
            if ( isOperation ( token ) ) {
                int val2 = stack.pop();
                int val1 = stack.pop();
                int tmp = performOperation ( token,  val1, val2);
                stack.push(tmp);
            }else
                stack.push(Integer.parseInt(token));
        }
        return stack.peek();
    }
    public boolean isOperation ( String s) {
        return (s.equals("+") || s.equals("-") || s.equals("/") || s.equals("*"));
    }
    public int performOperation ( String op, int val1, int val2) {
        int res=0;
        if(op.equals("+") ) { res = val1 + val2; }
        else if(op.equals("-") ) { res = val1 - val2; }
        else if(op.equals("/") ) { res = val1 / val2; }
        else if(op.equals("*") ) { res = val1 * val2; }
        return res;
    }

Log in to reply
 

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