• LeetCode——逆波兰表达式求值


    Q:计算逆波兰式(后缀表达式)的值
    运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式
    例如:

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

    A:使用栈,碰到符号就跳出来两个值计算再压入结果

    import java.util.Stack;
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack();
            for (int i = 0; i < tokens.length; i++) {
                try {
                    int num = Integer.parseInt(tokens[i]);
                    stack.push(num);
                } catch (Exception e) {
                    int a = stack.pop();
                    int b = stack.pop();
                    if (tokens[i].equals("+"))
                        stack.push(a + b);
                    else if (tokens[i].equals("-"))
                        stack.push(b - a);
                    else if (tokens[i].equals("*"))
                        stack.push(a * b);
                    else if (tokens[i].equals("/"))
                        stack.push(b / a);
                }
            }
            return stack.pop();
        }
    
  • 相关阅读:
    Fibonacci Numbers
    Fibonacci(...刷的前几道题没有记博客的习惯,吃了大亏)
    Fibonacci Check-up
    Pendant
    奥运
    Tr A
    A Simple Game
    Be the Winner
    John
    Being a Good Boy in Spring Festival(尼姆博弈)
  • 原文地址:https://www.cnblogs.com/xym4869/p/12426795.html
Copyright © 2020-2023  润新知