Accepted Java code with try catch


  • 1
    P

    Parce token with Integer,parceInt() and push it to stack. But when parcing fails with NumberFormatException we pop last two values and calculate.

    public int evalRPN(String[] tokens) {
        Stack<Integer> numbers = new Stack<Integer>();
        for(String token:tokens) {
        	try {
        		numbers.push(Integer.parseInt(token));
        	} catch (NumberFormatException e) {
        		int number2 = numbers.pop();
        		int number1 = numbers.pop();
        		if (token.equals("+")) {
        			numbers.push(number1 + number2);
        		} else if (token.equals("-")) {
        			numbers.push(number1 - number2);
        		} else if (token.equals("*")) {
        			numbers.push(number1 * number2);
        		} else if (token.equals("/")) {
        			numbers.push(number1 / number2);
        		} else {
        			throw new IllegalArgumentException("Incorrect token '" + token + "'");
        		}
        	}
        }
        
        return numbers.pop();
    }

Log in to reply
 

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