Evaluate Reverse Polish Notation runtime error //Last executed input: ["0","3","/"]//


  • 0
    L
    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length == 0) return 0;
        Stack<Integer> stack = new Stack<Integer>();
        int tmp = 0;
        for (int i = 0; i < tokens.length; i++){
            if (isDigit(tokens[i])) stack.push(Integer.parseInt(tokens[i]));
            else{
                int operand2 = stack.pop();
                int operand1 = stack.pop();
                char operator = tokens[i].charAt(0);
                switch (operator){
                    case '+': tmp = operand1 + operand2;stack.push(tmp);break;
                    case '-': tmp = operand1 - operand2;stack.push(tmp);break;
                    case '*': tmp = operand1 * operand2;stack.push(tmp);break;
                    case '/': tmp = operand1 / operand2;stack.push(tmp);break;
                    default : break;
                }
            }
        }
        return stack.pop();
    }
    
    public boolean isDigit(String s){
        return s != "+" && s != "-" && s != "*" && s != "/";
    }

  • 1
    S

    In java, comparing string should use equals not ==.

    So your code should change to this return !s.equals("+") && !s.equals("-") && !s.equals("*") && !s.equals("/");


  • 0
    L

    @Shangrilla Thanks for your reply and it helps me for passing the OJ. One more question is, I run the "!=" code in Eclipse and it will give me the right answer. I'm wondering why. Thank you in advance.


  • 0
    S

    I am not familiar with Java. I just remember comparing string should use equals not ==, the difference is like comparing its value or just its reference.


  • 0
    P

    In Java, everything is an object. For objects, == would check if they both pointing to same object rather than containing the same information


  • 0
    Y

    I got the same error with C++. Even tried to manually set 0/3 = 0 , but still got 0/3 = 18. Just curious, how did you fix it?


  • 0
    L

    I fixed it by modifying the isDigit method, replacing the comparison of String "==" by "equals". Do you mind pasting your code here?


Log in to reply
 

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