生活会辜负努力的人,但不会辜负一直努力的人

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

题目描述


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(); 
    } 
};

 

posted on 2018-09-16 16:39  何许亻也  阅读(225)  评论(0编辑  收藏  举报