• 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.转换数字,负数的存在。
    2.出栈时数字的顺序。
    3.好像没什么了……
    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
            stack<int> sk;
            int result;
            for(int i = 0 ; i < tokens.size(); i++)
            {
                if(isop(tokens[i]))
                {
                    int second = sk.top();
                    sk.pop();
                    int first = sk.top();
                    sk.pop();
                    
                    int midresult;
                    if(tokens[i] == "+") midresult = first + second;
                    else if(tokens[i] == "-")midresult = first - second;
                    else if(tokens[i] == "*")midresult = first * second;
                    else if(tokens[i] == "/")midresult = first / second;
                    
                    sk.push(midresult);
                    
                }
                else
                {
                    int tp = string2num(tokens[i]);
                    sk.push(tp);
                }
            }
            return sk.top();
            
        }
        bool isop(string s)
        {
            if(s== "+" ||s== "-" ||s== "*" ||s== "/"  )return 1;
            else return 0;
        }
        int string2num(string s)
        {
            int re =0 ;
            int flag = 0;
            int i = 0;
            if(s[0] == '-')
            {
                flag =1;
                i++;
            }
            for( ; i < s.size();i++)
            {
                re = re*10;
                re = re + s[i]-'0';
            }
            if(flag ==1)
            re = 0 -re;
            return re;
        }
    };
    

      

  • 相关阅读:
    服务管理命令
    软件管理
    Qt软件打包与发布(windeployqt工具)
    03
    第一章 BP神经网络
    代理模式 与 Spring AOP
    java 回调机制
    HashTable 实现
    实现Singleton模式
    BST 汇总
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3621164.html
Copyright © 2020-2023  润新知