Posts Evaluate Reverse Polish Notation
Post
Cancel

Evaluate Reverse Polish Notation

Problem Description

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

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

Note that division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

leetcode

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
class Solution {

    public int evalRPN(String[] tokens) {
        
        Set<String> operands = new HashSet<>();

        operands.add("+");
        operands.add("-");
        operands.add("*");
        operands.add("/");

        Stack<String> stack = new Stack<>();

        for(int i=0; i<tokens.length; i++){

            if(operands.contains(tokens[i])){

                int t = 0;

                int x = Integer.parseInt(stack.pop());
                int y = Integer.parseInt(stack.pop());

                if(tokens[i].equals("+")) t = x + y;
                if(tokens[i].equals("-")) t = y - x;
                if(tokens[i].equals("/")) t = y / x;
                if(tokens[i].equals("*")) t = x * y;

                stack.add(t + "");

            }else{

                stack.add(tokens[i]);

            }
        }

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

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