zoukankan      html  css  js  c++  java
  • Leetcode No.150 **

    根据逆波兰表示法,求表达式的值。

    有效的运算符包括 +-*/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

    说明:

    • 整数除法只保留整数部分。
    • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

    示例 1:

    输入: ["2", "1", "+", "3", "*"]
    输出: 9
    解释: ((2 + 1) * 3) = 9
    

    示例 2:

    输入: ["4", "13", "5", "/", "+"]
    输出: 6
    解释: (4 + (13 / 5)) = 6
    

    示例 3:

    输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
    输出: 22
    解释: 
      ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
    = ((10 * (6 / (12 * -11))) + 17) + 5
    = ((10 * (6 / -132)) + 17) + 5
    = ((10 * 0) + 17) + 5
    = (0 + 17) + 5
    = 17 + 5
    = 22

    解答:参考博客 http://www.cnblogs.com/grandyang/p/4247718.html
    逆波兰表示法主要是用于计算机的运算,人都是使用中缀序表达式如 a+b,计算机识别起来很费劲,故使用后缀序表达式 如 ab+,这对计算机来说很简单。
    这道题就相当于模拟计算机使用后缀序表达式的运算。
    思路:这道题采用堆栈很好做。顺便说一下,chat转换成int用函数atoi,int转换成char为itoa;string转换成int为stoi,int转换成string为to_string()


    //150
    int evalRPN(vector<string>& tokens)
    {
        if(tokens.empty()) return -1;
        if(tokens.size()==1) return   stoi(tokens[0]);
        stack<int> sta;
        int num1,num2;
        for(string str: tokens)
        {
            if(str!="+" && str!="-" && str!="*" && str!="/")
                sta.push(stoi(str));
            else
            {
                num2 = sta.top();
                sta.pop();
                num1 = sta.top();
                sta.pop();
                if(str=="+") sta.push(num1+num2);
                else if(str=="-") sta.push(num1-num2);
                else if(str=="*") sta.push(num1*num2);
                else if(str=="/") sta.push(num1/num2);
            }
        }
        return sta.top();
    }//150
  • 相关阅读:
    Scrapy爬虫快速入门
    python垃圾回收机制
    django项目的uwsgi方式启停脚本
    hdu 5504 GT and sequence
    python 在 for i in range() 块中改变 i 的值的效果
    linux 在终端中打开图形化文件管理器
    apache 支持 php
    Mysql 学习记录
    git 导入代码到已有仓库
    python import 自己的包
  • 原文地址:https://www.cnblogs.com/2Bthebest1/p/10882665.html
Copyright © 2011-2022 走看看