Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are+,-,*,/. Each operand may be an integer or another expression. Some examples:

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;
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/q-1993/p/10991038.html