Evaluate Expression

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Input Format

The only argument given is character array A.

Output Format

Return the value of arithmetic expression formed using reverse Polish Notation.

For Example

Input 1:
    A =   ["2", "1", "+", "3", "*"]
Output 1:
    9
Explaination 1:
    starting from backside:
    *: ( )*( )
    3: ()*(3)
    +: ( () + () )*(3)
    1: ( () + (1) )*(3)
    2: ( (2) + (1) )*(3)
    ((2)+(1))*(3) = 9
    
Input 2:
    A = ["4", "13", "5", "/", "+"]
Output 2:
    6
Explaination 2:
    +: ()+()
    /: ()+(() / ())
    5: ()+(() / (5))
    1: ()+((13) / (5))
    4: (4)+((13) / (5))
    (4)+((13) / (5)) = 6
public class Solution {
    public int evalRPN(String[] A) {
        Stack<Integer> st = new Stack<>();
        for (int i = 0; i < A.length; i++) {
            if (A[i].compareTo("+") == 0) {
                int num1 = st.pop();
                int num2 = st.pop();
                st.push(num2 + num1);
            } else if (A[i].compareTo("-") == 0) {
                int num1 = st.pop();
                int num2 = st.pop();
                st.push(num2 - num1);
            } else if (A[i].compareTo("*") == 0) {
                int num1 = st.pop();
                int num2 = st.pop();
                st.push(num2 * num1);
            } else if (A[i].compareTo("/") == 0) {
                int num1 = st.pop();
                int num2 = st.pop();
                st.push(num2 / num1);
            } else {
                st.push(Integer.parseInt(A[i]));
            }
        }
        return st.pop();
    }
}

Last updated