Thinking process

public class Solution {
    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length == 0) return 0;
        HashSet<String> operators = new HashSet<>(Arrays.asList("+", "-", "*", "/"));
        Stack<Integer> stack = new Stack<>();//numbers

        for (String str : tokens) {
            if (operators.contains(str)) {
                int num2 = stack.isEmpty() ? 0 : stack.pop();
                int num1 = stack.isEmpty() ? 0 : stack.pop();
                stack.push(calculate(num1, num2, str));
            } else {
                stack.push(Integer.valueOf(str));
            }
        }

        return stack.isEmpty() ? 0 : stack.pop();
    }

    private int calculate(int num1, int num2, String operator) {
        int result = 0;

        if (operator.equals("+")) {
            result = num1 + num2;
        } else if (operator.equals("-")) {
            result = num1 - num2;
        } else if (operator.equals("*")) {
            result = num1 * num2;
        } else {
            if (num2 == 0) result = 0;
            else result = num1 / num2;
        }

        return result;
    }
}

results matching ""

    No results matching ""