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

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

    解题思路:

      题目考察栈的使用,Reverse Polish Notation也是《数据结构与算法分析--C语言描述》一书讲解栈时所举例子之一。

      计算逆波兰表达式时,先定义一个栈对象stack,遍历给定的表达式,遇到数字时将其push进stack中,遇到运算符时,从stack中pop出两个操作数。

      根据操作符进行相应计算后,将结果push进stack中。

      最终stack中应该只有一个元素,即表达式的计算结果。

    代码:

     1 class Solution {
     2 public:
     3     int evalRPN(vector<string> &tokens) {
     4         stack <int> nums;
     5         for (auto token : tokens) {
     6             if (token == "+" || token == "-" || token == "*" || token == "/") {
     7                 int tmp1 = nums.top();
     8                 nums.pop();
     9                 int tmp2 = nums.top();
    10                 nums.pop();
    11                 nums.push(cal(tmp2,tmp1,token));
    12             } else {
    13                 nums.push(stoi(token));
    14             }
    15         }
    16         return nums.top();
    17     }
    18     
    19     int cal(int a, int b, const string& token) {
    20         if (token == "+")
    21             return a+b;
    22         else if (token == "-")
    23             return a-b;
    24         else if (token == "*")
    25             return a*b;
    26         else
    27             return a/b;
    28     }
    29 };
  • 相关阅读:
    发送邮件程序
    T-SQL存储过程、游标
    GPS经纬度换算成XY坐标
    开博了
    你应该知道的 50 个 Python 单行代码
    想提升java知识的同学请进
    adb工具包使用方法
    红米note3刷安卓原生
    hadoop 使用和javaAPI
    django学习——url的name
  • 原文地址:https://www.cnblogs.com/gsz-/p/9368008.html
Copyright © 2011-2022 走看看