当前位置 : 主页 > 网络编程 > lua >

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

来源:互联网 收集:自由互联 发布时间:2021-06-23
import java.util.* ; public class Solution { public int evalRPN(String[] tokens) { // int temp = 0; StackInteger stack = new StackInteger (); for ( int i = 0; i tokens.length; i++ ){ if (tokens[i].equals("+") || tokens[i].equals("-") || tok
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;
        }
    }
}
网友评论