zoukankan      html  css  js  c++  java
  • 2、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
    

     //判断字符串是否是数字,如果是就压栈,不是就弹出2个元素进行计算,将计算结果压栈

    //最后栈顶元素即为所求
    class Solution { 
    public:    
        int evalRPN(vector<string> &tokens) { 
            stack<int> st;        
            for (int i = 0; i < tokens.size(); i++){ 
                if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") { 
                    int temp = 0;                
                    int a = st.top(); 
                    st.pop();                
                    int b = st.top(); 
                    st.pop();                
                    if (tokens[i] == "+") { temp = b + a; } 
                    else if (tokens[i] == "-") { temp = b - a; } 
                    else if (tokens[i] == "*") { temp = b * a; } 
                    else { temp = b / a; }                
                    st.push(temp); 
                } 
                else { 
                    st.push(stoi(tokens[i])); 
                } 
            }        
            return st.top(); 
        } 
    };
  • 相关阅读:
    块级作用域
    作用域变量 var
    unkown类型
    generator (2)
    generator (1)
    generator
    索引类型
    XML 特殊字符处理和 CDATA
    15 个实用的 PHP 正则表达式
    论MySQL数据库中两种数据引擎的差别
  • 原文地址:https://www.cnblogs.com/fuqia/p/9656514.html
Copyright © 2011-2022 走看看