Java: why it says wrong answer. I have tested with my own compiler


  • 0
    X
    public class Solution {
        public int evalRPN(String[] tokens) {
            int rst = 0;
            int ptr1 = 0, ptr2 = 0;
            int operand1 = 0, operand2 = 0;
            if (tokens.length == 0) {
                return rst;
            }
            if (tokens.length == 1) {
                return Integer.parseInt(tokens[0]);
            }
            while (ptr1 != tokens.length) {
                if (tokens[ptr1] == "+" || tokens[ptr1] == "-" || tokens[ptr1] == "*" || tokens[ptr1] == "/") {
                    ptr2 = ptr1 - 1;
                    if (tokens[ptr2] == "") {
                        operand2 = rst;
                        while (tokens[ptr2] == "") {
                            ptr2--;
                        }
                        operand1 = Integer.parseInt(tokens[ptr2]);
                        rst = compute(operand1, operand2, tokens[ptr1]);
                        tokens[ptr1] = "";
                        tokens[ptr2] = "";
                    } else {
                        operand2 = Integer.parseInt(tokens[ptr2]);
                        tokens[ptr2--] = "";
                        if (tokens[ptr2] == "") {
                            operand1 = rst;
                        } else {
                            operand1 = Integer.parseInt(tokens[ptr2]);
                            tokens[ptr2] = "";
                        }
                        rst = compute(operand1, operand2, tokens[ptr1]);
                        tokens[ptr1] = "";
                    }
                }
                ptr1++;
            }
            return rst;
        }
        private int compute(int op1, int op2, String operator) {
            if (operator == "+") {
                return op1 + op2;
            }
            if (operator == "-") {
                return op1 - op2;
            }
            if (operator == "*") {
                return op1 * op2;
            }
            if (operator == "/") {
                return op1 / op2;
            }
            return 9999;
        }
    }
    

    The test case is ["3", "-4", "+"]
    It says the output is 0 instead of -1. But my own compiler outputs the correct result which is -1.
    Anyone has an idea what is going on?


  • 0
    O

    I also have this kind of problem. I tested my code in my local machine and it's right.


  • 0
    O

    tokens[ptr1] == "+" || tokens[ptr1] == "-" || tokens[ptr1] == "*" || tokens[ptr1] == "/"

    Try to use .equal() for string comparison.


Log in to reply
 

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