Posts Evaluate Expression
Post
Cancel

Evaluate Expression

PROBLEM DESCRIPTION

An arithmetic expression is given by a character array A of size N. Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each character may be an integer or an operator.

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class Solution {
    public int evalRPN(ArrayList<String> A) {

        Stack<String> stack = new Stack<String>();
        Set<String> set = new HashSet<>();
        set.add("+");
        set.add("-");
        set.add("*");
        set.add("/");
        

        for(int i=0; i<A.size(); i++){
            
            String x = A.get(i);

            //Operator found. Pop two elements from stack and calculate
            if(set.contains(x)){
                
                int a = Integer.parseInt(stack.pop());
                int b = Integer.parseInt(stack.pop());

                int ans = calculate(b, a, x);
                stack.push(ans+"");

            }else{ //Current element is a number
                stack.push(x);
            }
            
        }

        return Integer.parseInt(stack.pop());

    }

    public int calculate(int a, int b, String op) {

        int ans = 0;

        if(op.equals("+")){
            ans = a+b;
        }else if(op.equals("-")){
            ans=a-b;
        }else if(op.equals("*")){
            ans=a*b;
        }else{
            ans=a/b;
        }

        return ans;

    }

}
This post is licensed under CC BY 4.0 by the author.