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.
public int evalRPN(String[] tokens) { if (tokens == null || tokens.length == 0) return 0; Stack<Integer> stack = new Stack<Integer>(); int tmp = 0; for (int i = 0; i < tokens.length; i++){ if (isDigit(tokens[i])) stack.push(Integer.parseInt(tokens[i])); else{ int operand2 = stack.pop(); int operand1 = stack.pop(); char operator = tokens[i].charAt(0); switch (operator){ case '+': tmp = operand1 + operand2;stack.push(tmp);break; case '-': tmp = operand1 - operand2;stack.push(tmp);break; case '*': tmp = operand1 * operand2;stack.push(tmp);break; case '/': tmp = operand1 / operand2;stack.push(tmp);break; default : break; } } } return stack.pop(); } public boolean isDigit(String s){ return s != "+" && s != "-" && s != "*" && s != "/"; }
In java, comparing string should use equals not ==.
equals
==
So your code should change to this return !s.equals("+") && !s.equals("-") && !s.equals("*") && !s.equals("/");
return !s.equals("+") && !s.equals("-") && !s.equals("*") && !s.equals("/");
@Shangrilla Thanks for your reply and it helps me for passing the OJ. One more question is, I run the "!=" code in Eclipse and it will give me the right answer. I'm wondering why. Thank you in advance.
I am not familiar with Java. I just remember comparing string should use equals not ==, the difference is like comparing its value or just its reference.
In Java, everything is an object. For objects, == would check if they both pointing to same object rather than containing the same information