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.

Code runs fine on either Eclipse or cmd command but always gets runtime error on LC OJ

–1 vote
613 views

Here is my code. I tried it on Eclipse and on Windows cmd command line. They both give the correct result. But on LC it always complains for an Arithmetic Exception saying that it is divided by zero.I have looked through similar questions on LC Discussion, tried most of them, but still cannot get it accepted. Could someone have a look and point out the problem to me?

Thank you a lot!!!

public int evalRPN(String[] tokens) {
    Stack<Integer> numbers = new Stack<Integer>();
    int l = tokens.length;
    String operators = "+-*/";
    for (int i=0; i<l; i++){
        if (operators.contains(tokens[i])){
            int newN;
            int newN1 = numbers.pop();
            int newN2 = numbers.pop();
            if (tokens[i] == "+"){
                    newN = newN1 + newN2;
            }
            else if (tokens[i] == "-"){
                    newN = newN2 - newN1;
            }
            else if (tokens[i] == "*"){
                    newN = newN1 * newN2;
            }
            else{
                    newN = newN2 / newN1;
            }
            numbers.push(newN);
        }

        else{
            numbers.push(Integer.parseInt(tokens[i]));
        }
    }
    return numbers.get(0);
}
asked Apr 7 in Evaluate Reverse Polish Notation by Yunying (110 points)

1 Answer

0 votes

Hi, you need to use string1.equals(string2) to compare two strings, do not use "==" .

answered May 6 by ricky (140 points)

...