What is problem of my code? It's working correctly in my machine..


  • 0
    C
    import java.util.ArrayList;
    

    public class Solution {
    public static int evalRPN(String[] tokens) {
    ArrayList<Integer> operators = new ArrayList<Integer>();

        for(int i = 0; i < tokens.length; i++){
            if(tokens[i] == "+" || tokens[i] == "-" || 
            		tokens[i] == "*" || tokens[i] == "/"){
                operators.add(i);
            }
        }
        int result = Integer.parseInt(tokens[0]);
        for(int i = 0; i < operators.size(); i++){
            int operPos = operators.get(i);
            String operator = tokens[operPos];
            result = 0;
            int operandOne = 0;// = Integer.parseInt(tokens[operPos - 1]);
            int operandTwo = 0;// = Integer.parseInt(tokens[operPos - 2]);
            int operOnePos = operPos - 1;
            for(; operOnePos >= 0; operOnePos--){
                if(tokens[operOnePos] != ""){
                    operandOne = Integer.parseInt(tokens[operOnePos]);
                    //System.out.println(operOnePos);
                    break;
                }
            }
            int operTwoPos = operOnePos - 1;
            for(; operTwoPos >= 0; operTwoPos--){
                if(tokens[operTwoPos] != ""){
                    operandTwo = Integer.parseInt(tokens[operTwoPos]);
                    //System.out.println(operTwoPos);
                    break;
                }
                
            }
    
            switch(operator){
                case "+": result = operandOne + operandTwo;
                          break;
                case "-": result = operandTwo - operandOne;
                          break;
                case "*": result = operandOne * operandTwo;
                          break;
                case "/": result = operandTwo / operandOne;
                          break;
            }
            
            tokens[operPos] = Integer.toString(result);
            tokens[operOnePos] = "";
            tokens[operTwoPos] = "";
        }
        
        return result;
    }
    
    public static void main(String[] args){
    	String[] test = {"10","6","9","3","+","-11","*","/","","17","+","5","+"};
    	
    	System.out.println(evalRPN(test));
    }
    

    }

    It's working all fine in my IDE, but it didn't pass the test, saying that [3, -4, +] is 3.
    but when I run it, it's output is -1


  • 1
    O

    if(tokens[i] == "+" || tokens[i] == "-" ||
    tokens[i] == "*" || tokens[i] == "/")

    Try to use .equals() for string comparison.


Log in to reply
 

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