It runs on Eclipse, but it does not work here. Can someone help me figure out the reason? Thanks in advance!


  • 1
    J

    import java.util.Stack;

    public class Solution {

    public int evalRPN(String[] tokens) {
    	int len = tokens.length;
    	int previous_value, current_value, i=0;
    	Stack st = new Stack();
    	for (i=0; i<len; i++){
    		switch(tokens[i]) {
    			case "+":
    				previous_value=(Integer)st.pop();
    				current_value=(Integer)st.pop();
    				st.push(previous_value+current_value);
    				break;
    			case "-": 
    				previous_value=(Integer)st.pop();
    				current_value=(Integer)st.pop();
    				st.push(current_value-previous_value);
    				break;
    			case "*": 
    				previous_value=(Integer)st.pop();
    				current_value=(Integer)st.pop();
    				st.push(previous_value*current_value);
    				break;
    			case "/": 
    				previous_value=(Integer)st.pop();
    				current_value=(Integer)st.pop();
    				st.push(current_value/previous_value);
    				break;
    			default:
    				st.push(Integer.valueOf(tokens[i]));
    				break;
    			}
    	}
    	return (Integer)st.pop();
    }
    

    }


  • 2
    L

    The online judge uses Java 6. The switch statement with String has been introduced in Java 7.


  • 0
    S

    Please correct your code format, select all then click {} button. Thanks.


  • 0
    M

    The problem is with the default: condition, it is not just Integer.valueOf(tokens[i]), it more than that, think about string tokens whose length is greater than 1, Eg : {18}. In this case, the stack would be 1 8 where 8 is the top, but it should have been 18


  • 0
    S

    Try Integer.parseInt(tokens[i]) instead of Integer.valueOf(tokens[i]). This can parse an integer of more than one decimal point.
    that might work.. :)


  • 0
    Y

    I met the same problem, at last I changed the type “Integer” to int, the test accepted


  • 0
    H

    The switch statement with String can be OK in my code. The online judge uses Java 7


Log in to reply
 

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