zoukankan      html  css  js  c++  java
  • evaluate-reverse-polish-notati 计算逆波兰式的值

    题目:

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

    示例:

    输入:["2", "1", "+", "3", "*"]  输出:9

    代码:

     1 class Solution {
     2 public:
     3     /**
     4      * 
     5      * @param tokens string字符串vector 
     6      * @return int整型
     7      */
     8     int evalRPN(vector<string>& tokens) {
     9         // write code here
    10         stack<int> st;
    11         for(auto token : tokens) {
    12             if(token == "+" || token == "-" || token == "*" || token == "/"){
    13                 int num_a = st.top();st.pop();
    14                 int num_b = st.top();st.pop();
    15                 if(token == "+" )
    16                     st.push((num_b + num_a));
    17                 if(token == "-" )
    18                     st.push((num_b - num_a));
    19                 if(token == "*" )
    20                     st.push((num_b * num_a));
    21                 if(token == "/" )
    22                     st.push((num_b / num_a));
    23             }
    24             else{
    25                 stringstream strs;
    26                 strs << token;
    27                 int temp;
    28                 strs >> temp;
    29                 st.push(temp);
    30             }
    31         } 
    32         return st.top();
    33     }
    34 };

    我的笔记:

      根据操作符在后的特性,利用堆栈来完成计算。

      关于stringstream操作详见:https://www.cnblogs.com/john1015/p/13216702.html

  • 相关阅读:
    vscode 基本知识以及如何配置 C++ 环境
    计算机视觉
    GitHub 大事件
    tf 2.0
    AI 公司与比赛
    Faster RCNN 学习与实现
    pycahrm安装说明
    python 并发之线程
    python 并发之进程
    python socketserver ftp上传功能
  • 原文地址:https://www.cnblogs.com/john1015/p/13216576.html
Copyright © 2011-2022 走看看