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:

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

    思路:
    逆波兰表达式,使用一个栈来计算。
    代码:
     1     int evalRPN(vector<string> &tokens) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         int l = tokens.size();
     5         if(l == 0)
     6             return 0;
     7         stack<int> nums;
     8         for(int i = 0; i < l; i++){
     9             string tmp = tokens[i];
    10             if(tmp == "+"){
    11                 int num1 = nums.top();
    12                 nums.pop();
    13                 int num2 = nums.top();
    14                 nums.pop();
    15                 nums.push(num1 + num2);
    16             }
    17             else if(tmp == "-"){
    18                 int num1 = nums.top();
    19                 nums.pop();
    20                 int num2 = nums.top();
    21                 nums.pop();
    22                 nums.push(num2 - num1);
    23             }
    24             else if(tmp == "*"){
    25                 int num1 = nums.top();
    26                 nums.pop();
    27                 int num2 = nums.top();
    28                 nums.pop();
    29                 nums.push(num1 * num2);
    30             }
    31             else if(tmp == "/"){
    32                 int num1 = nums.top();
    33                 nums.pop();
    34                 int num2 = nums.top();
    35                 nums.pop();
    36                 nums.push(num2 / num1);
    37             }
    38             else
    39                 nums.push(atoi(tmp.c_str()));
    40         }
    41         return nums.top();
    42     }
  • 相关阅读:
    寄存器英文全称
    汇编指令介绍
    汇编指令的基本知识
    第一篇
    Windows下让Git记住用户名密码(https)
    javascript 汉字拼音排序
    KO.js学习笔记(一)
    学javascript突发奇想,只用浏览器就能转换进制
    谨此纪念我的技术成长之路
    委托与事件
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3447010.html
Copyright © 2011-2022 走看看