Clean JAVA Code


  • 1
    A
    public int evalRPN(String[] tokens) {
    	Stack<String> st = new Stack<String>();
    	for (String token : tokens) {
    		if (token.equals("+")) {
    			int b = Integer.parseInt(st.pop());
    			int a = Integer.parseInt(st.pop());
    			st.push(String.valueOf(a + b));
    		} else if (token.equals("-")) {
    			int b = Integer.parseInt(st.pop());
    			int a = Integer.parseInt(st.pop());
    			st.push(String.valueOf(a - b));
    		} else if (token.equals("*")) {
    			int b = Integer.parseInt(st.pop());
    			int a = Integer.parseInt(st.pop());
    			st.push(String.valueOf(a * b));
    		} else if (token.equals("/")) {
    			int b = Integer.parseInt(st.pop());
    			int a = Integer.parseInt(st.pop());
    			if(b == 0) throw new IllegalArgumentException("divisor is 0");
    			st.push(String.valueOf(a / b));
    		} else
    			st.push(token);
    	}
    	return Integer.parseInt(st.pop());
    }

  • 0

    @arif32 Good solution! One quick question: could you explain how does your code handle the case "a / b" where b is zero? Thanks! I do not think your code will pass when I read it but your code is actually accepted by LC.


  • 0
    A

    @shurui You are right, I guess I was just lucky that input did not have a divide by zero case. I just added code to handle it.


Log in to reply
 

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