• leetcode-Evaluate the value of an arithmetic expression in Reverse Polish Notation


    leetcode 逆波兰式求解

    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 {
         public int evalRPN(String[] tokens) {
             Stack<Integer> stack = new Stack<Integer>();
            int tmp;
            for(int i = 0; i<tokens.length; i++){
                if("+".equals(tokens[i])){
                    int a = stack.pop();
                    int b = stack.pop();
                    stack.add(b+a);
                }
                else if("-".equals(tokens[i])){
                    int a = stack.pop();
                    int b = stack.pop();
                    stack.add(b-a);
                }
                else if("*".equals(tokens[i])){
                    int a = stack.pop();
                    int b = stack.pop();
                    stack.add(b*a);
                }
                else if("/".equals(tokens[i])){
                    int a = stack.pop();
                    int b = stack.pop();
                    stack.add(b/a);
                }
                else{
                    stack.add(Integer.parseInt(tokens[i]));
                }
                
                
            }
            return stack.pop();
         }
    }

    根据你波兰式求值。看到逆波兰式可以想到栈,扫描表达式,遇到数字则将数字入栈,遇到运算符,时,则从栈顶弹出两个元素,后弹出的元素在运算符的左边,先弹出的元素在元素符的右边,执行运算,将结果入栈。扫描结束后,栈中的元素只剩下一个,即逆波兰式的值

  • 相关阅读:
    吴恩达深度学习与神经网络
    吴恩达机器学习的ppt以及作业编程练习题答案(别人总结的)
    关于机器学习的小科普
    质因数分解
    FFT
    Luogu P1262 间谍网络
    关于次短路
    Luogu P1955 [NOI2015]程序自动分析
    Luogu P1041传染病控制
    Bzoj 1731 POJ 3169 Luogu P4878 Layout
  • 原文地址:https://www.cnblogs.com/qj4d/p/7078478.html
Copyright © 2020-2023  润新知