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

      

  • 相关阅读:
    Python+MySQL学习笔记(一)
    MySQL的基本操作
    2016.08.15
    使用vue为image的src动态赋值
    json对象与json字符串的转化
    js三元运算符
    uniapp vue中的短信验证码
    设计模式
    回调函数
    自定义注解
  • 原文地址:https://www.cnblogs.com/xww115/p/11195387.html
Copyright © 2020-2023  润新知