zoukankan      html  css  js  c++  java
  • 150. 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

    题目含义:逆波兰计算,大话数据结构中讲到过,用一个栈来实现后缀表达式的计算。
    思路:从左到右遍历表达式的每个数字和字符,遇到数字就进栈,遇到符号,就将栈顶的两个数字取出(注意第一次取出的是右操作数,第二次取出的栈顶数字是左操作数),进行运算,将运算结果压栈,一直到最终获得计算结果(最终的栈顶数字)

     1     public int evalRPN(String[] tokens) {
     2         int a,b;
     3         Stack<Integer> S = new Stack<Integer>();
     4         for (String s : tokens) {
     5             if(s.equals("+")) {
     6                 S.add(S.pop()+S.pop());
     7             }
     8             else if(s.equals("/")) {
     9                 b = S.pop();
    10                 a = S.pop();
    11                 S.add(a / b);
    12             }
    13             else if(s.equals("*")) {
    14                 S.add(S.pop() * S.pop());
    15             }
    16             else if(s.equals("-")) {
    17                 b = S.pop();
    18                 a = S.pop();
    19                 S.add(a - b);
    20             }
    21             else {
    22                 S.add(Integer.parseInt(s));
    23             }
    24         }
    25         return S.pop();        
    26     }
     
  • 相关阅读:
    分布式架构总汇【转】
    spring注解
    lombok安装和使用
    dubbo配置
    关于dubbo的负载均衡
    maven工作的过程
    android基础---->子线程更新UI
    JavaScript中有时候需要获取当前的时间戳
    Ubuntu 安装mysql
    nodejs 语法很特别的地方
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7727522.html
Copyright © 2011-2022 走看看