Easy to understand Java code


  • 0
    C
    class Solution {
        public int evalRPN(String[] tokens) {
            Stack<String> stack = new Stack();
            for(int i=0; i<tokens.length; i++){
                if(!isOperator(tokens[i])){
                    stack.push(tokens[i]);    
                } else {
                    int a = Integer.parseInt(stack.pop());
                    int b = Integer.parseInt(stack.pop());
                    int temp = op(b,a, tokens[i]);
                    String stemp = String.valueOf(temp);
                    stack.push(stemp);
                }
            }
            return Integer.parseInt(stack.pop());
        }
        public boolean isOperator(String s){
            return (s.equals("*") || s.equals("/") || s.equals("+") || s.equals("-"));
        }   
        public int op(int a, int b, String s){
            if(s.equals("*")){
                return a*b;
            }
            if(s.equals("/")){
                return a/b;
            }
            if(s.equals("+")){
                return a+b;
            }
            return a-b;
        } 
    }
    

Log in to reply
 

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