Easy Java solution with Stack


  • 0
    E
    public class Solution {
        public int evalRPN(String[] tokens) {
            Stack<Integer>stack=new Stack<Integer>();
            int res=0;
            for(int i=0;i<tokens.length;i++){
                if(!tokens[i].equals("+") && !tokens[i].equals("-") && !tokens[i].equals("*") && !tokens[i].equals("/")){
                    int val=Integer.parseInt(tokens[i]);
                    stack.push(val);
                }
                int val1=0,val2=0;
                switch (tokens[i]){
                    case "+":
                        val1=stack.pop();
                        val2=stack.pop();
                        res=val2+val1;
                        stack.push(res);
                        break;
                    case "-":
                        val1=stack.pop();
                        val2=stack.pop();
                        res=val2-val1;
                        stack.push(res);
                        break;
                    case "*":
                        val1=stack.pop();
                        val2=stack.pop();
                        res=val2*val1;
                        stack.push(res);
                        break;
                    case "/":
                        val1=stack.pop();
                        val2=stack.pop();
                        res=val2/val1;
                        stack.push(res);
                        break;
                }
                
            }
            if(res==0 && stack.peek()!=0){
                return stack.peek();
            }
            return res;
        }
    }
    

Log in to reply
 

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