Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are+,-,*

import java.util.*;
public class Solution {
    public int evalRPN(String[] tokens) {
       
        //int temp = 0;
       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("/")){
                int a = stack.pop();
                int b = stack.pop();
                //temp =  calculateMethod(tokens[i],a,b);
                stack.push(calculateMethod(tokens[i],a,b));
            }else{
                stack.push(Integer.parseInt(tokens[i]));
            }
        }
        return stack.pop();
    }

    public  int calculateMethod(String tokens, int a, int b)  {
        if(tokens.equals("+")){
            return b + a;
        }else if(tokens.equals("-")){
            return b - a;
        }else if(tokens.equals("*")){
            return b * a;
        }
        else{
            //int c= b/a;
           // System.out.println(c);
            return b/a;
        }
    }
}

 

上一篇:nginx 基本安全优化


下一篇:Batch - FOR /F Delims 和 Tokens 用法