zoukankan      html  css  js  c++  java
  • 面试题42:计算逆波兰表达式(RPN)

      这是一个比较简单的题目,借助栈可以轻松实现逆波兰表达式。

    题目描述:

    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 class Solution {
     2 public:
     3     int evalRPN(vector<string> &tokens) {
     4         stack<int> s;
     5         for(string str : tokens){
     6             if(str == "+" || str == "-" || str == "*" || str == "/"){
     7                 int a = s.top();s.pop();
     8                 int b = s.top();s.pop();
     9                 if(str == "+"){
    10                     s.push(b+a);
    11                 }else if(str == "-"){
    12                     s.push(b - a);
    13                 }else if(str == "*"){
    14                     s.push(b*a);
    15                 }else{
    16                     s.push(b/a);
    17                 }
    18             }else{
    19                 s.push(std::stoi(str));
    20             }
    21         }
    22         return s.top();
    23     }
    24 };
  • 相关阅读:
    Java工具类
    集合 -- 嵌套表
    集合--索引表
    第一章
    记录Record
    序列Sequence
    操纵数据库 DML
    表的集合操作
    视图
    索引
  • 原文地址:https://www.cnblogs.com/wxquare/p/6950095.html
Copyright © 2011-2022 走看看