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


  • -1
    Y

    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);
    }

  • 1
    R

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


Log in to reply
 

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