其他分享
首页 > 其他分享> > evaluate-reverse-polish-notation

evaluate-reverse-polish-notation

作者:互联网

题目:

 

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:

 

 

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

  

 

 

解一:

 

 

 

 

 

 

 

 

import java.util.Stack;

public class Solution {
    private final static String ADD = "+";
    private final static String SUBTRACT = "-";
    private final static String MULTIPLY = "*";
    private final static String DIVIDE = "/";
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();
        int op1,op2, result=0;
        if(tokens.length<3){
            return Integer.parseInt(tokens[0]);
        }
        for(int i = 0; i<tokens.length; i++){
            if (isOperator(tokens[i])){
                op2 = (stack.pop()).intValue();
                op1 = (stack.pop()).intValue();
                result = evaluateSingleOperator(tokens[i],op1,op2);
                stack.push(new Integer(result));
            }else {
                stack.push(new Integer(Integer.parseInt(tokens[i])));
            }
        }
        return result;
        
    }
    private boolean isOperator(String token){
        return (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"));
    }
 
    private int evaluateSingleOperator(String operator, int op1 , int op2){
        int result = 0;
 
        switch (operator){
            case ADD:
                result = op1 + op2;
                break;
            case SUBTRACT:
                result = op1- op2;
                break;
            case MULTIPLY:
                result = op1 * op2;
                break;
            case DIVIDE:
                result = op1 / op2;
                break;
        }
 
        return result;
    }
}

  

 

标签:reverse,notation,int,evaluate,private,Stack,static,final,String
来源: https://www.cnblogs.com/xww115/p/11195387.html