Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

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

–1 vote
188 views
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 != "/";
}
asked Dec 3 in Evaluate Reverse Polish Notation by lby8833 (110 points)

1 Answer

+1 vote

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

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

answered Dec 3 by Shangrila (11,500 points)

@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.

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.

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


...