My Java solution covering invalid inputs, divided by zero error.


  • 0
    L
    public class Solution {
    public int evalRPN(String[] tokens) {        
        int result = Integer.MIN_VALUE;
        Stack<Integer> stack = new Stack<Integer>();
        for(int i=0; i< tokens.length; i++){
            if(tokens[i].equals("-") || tokens[i].equals("+") || tokens[i].equals("*") || tokens[i].equals("/")){
                try{
                    switch (tokens[i].charAt(0)){
                        case '+' :
                            result = stack.pop() + stack.pop();
                            break;
                        case '-' :
                            result = stack.pop();
                            result = stack.pop() - result;
                            break;
                        case '*' :
                            result = stack.pop() * stack.pop();
                            break;
                        case '/' :
                            result = stack.pop();
                            if (result == 0)
                                return Integer.MIN_VALUE;
                            result = stack.pop() / result;
                    }
                    stack.push(result);
                }catch(EmptyStackException e){
                    return Integer.MIN_VALUE;
                }
                continue;
            }
            try{
                stack.push(Integer.parseInt(tokens[i]));
            }catch(NumberFormatException e){
                return Integer.MIN_VALUE;
            }
        }
        if (!stack.isEmpty())
            result = stack.pop();
        return stack.isEmpty() ? result : Integer.MIN_VALUE;
    }
    

    }


Log in to reply
 

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