Solution using JavaStack


  • 0
    M

    src : https://www.youtube.com/watch?v=zMDm2MbRG6w

    public int evalRPN(String[] tokens) {
            
            Stack<String> operands = new Stack<String>();
            
            Integer num1 = null, num2 = null, result = null;
            
            for (String t : tokens) {
                
                switch (t) {
                    
                    case "+" :
                        num2 = Integer.parseInt(operands.pop());
                        num1 = Integer.parseInt(operands.pop());
                        result = num1 + num2;
                        operands.push(""+result);  
                        break;
                        
                    case "-" :
                        num2 = Integer.parseInt(operands.pop());
                        num1 = Integer.parseInt(operands.pop());
                        result = num1 - num2;
                        operands.push(""+result);  
                        break; 
                        
                    case "*" :
                        num2 = Integer.parseInt(operands.pop());
                        num1 = Integer.parseInt(operands.pop());
                        result = num1 * num2;
                        operands.push(""+result);  
                        break;
                        
                    case "/" :
                        num2 = Integer.parseInt(operands.pop());
                        num1 = Integer.parseInt(operands.pop());
                        result = num1 / num2;
                        operands.push(""+result);  
                        break;
                        
                    default :
                        try {
                            operands.push(t);
                        } catch (NumberFormatException ex) {
                            System.out.println("Not a valid number");
                        }             
                }  
            }
            return Integer.parseInt(operands.pop());
        }
    

Log in to reply
 

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