My code works on my on OSX machine but get a different result on the website


  • 0
    B

    My test code

    import java.util.*;
    public class ReversePolishNotation {
    public static int evalRPN(String[] tokens) {
        Integer res = Integer.parseInt(tokens[0]);
        //String[] notation = {"2", "1", "+", "3", "*"};
        // for (String a : notation) {
        //      System.out.println(a);
        // }
        Stack<String> stk = new Stack<String>();
        for(int i = 0; i < tokens.length; i ++){
            if(tokens[i] != "/" && tokens[i] != "*" && tokens[i] != "+" && tokens[i] != "-")
                stk.push(tokens[i]);
            else
            {
                String ope = tokens[i];
                int left = Integer.parseInt(stk.pop());
                int right = Integer.parseInt(stk.pop());
                if(ope.equals("+")) res = left + right;
                else if (ope.equals("-")) res = left - right;
                else if(ope.equals("*")) res = left * right;
                else res = left / right;
                stk.push(res.toString());
            }
        }
        return res;
        // System.out.println(res + "");
    }
    public static void main(String[] args) {
        String[] str = {"3","-4","+"};
        int res = evalRPN(str);
        System.out.println(res+"");
    }
    

    }

    My submitted code

    public class Solution {
    public int evalRPN(String[] tokens) {
                Integer res = Integer.parseInt(tokens[0]);
        //String[] notation = {"2", "1", "+", "3", "*"};
       // for (String a : notation) {
      //      System.out.println(a);
       // }
        Stack<String> stk = new Stack<String>();
        for(int i = 0; i < tokens.length; i ++){
            if(tokens[i] != "/" && tokens[i] != "*" && tokens[i] != "+" && tokens[i] != "-")
                stk.push(tokens[i]);
            else
            {
                String ope = tokens[i];
                int left = Integer.parseInt(stk.pop());
                int right = Integer.parseInt(stk.pop());
                if(ope.equals("+")) res = left + right;
                else if (ope.equals("-")) res = left - right;
                else if(ope.equals("*")) res = left * right;
                else res = left / right;
                stk.push(res.toString());
            }
        }
        return res;
       // System.out.println(res + "");
    }
    

    The website said:
    Input: ["3","-4","+"]
    Output: 3
    Expected: -1

    But I got -1 on my own machine


  • 0
    Y

    maybe you could try using equals for comparison, instead of == !=


  • 0
    B

    yes, you're right. equals method compares the content of the object but == and != compare the reference of the object


Log in to reply
 

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