leetcode #150 in cpp

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


Code:

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> stk; 
        int res; 
        int a,b; 
        for(int i = 0; i < tokens.size(); i ++){
            string temp = tokens[i];
            if(temp == "*"){
                a = stk.top();
                stk.pop();
                b = stk.top();
                stk.pop();
                stk.push(a*b);
            }else if(temp == "/"){
                a = stk.top();
                stk.pop();
                b = stk.top();
                stk.pop();
                stk.push(b/a);
            }else if(temp == "+"){
                a = stk.top();
                stk.pop();
                b = stk.top();
                stk.pop();
                stk.push(a+b);
            }else if(temp == "-"){
                a = stk.top();
                stk.pop();
                b = stk.top();
                stk.pop();
                stk.push(b-a);
            }else{
                stk.push(stoi(temp));
            }
        }
        return stk.top(); 
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章