150. Evaluate Reverse Polish Notation

来源:互联网 发布:异常断电数据库 编辑:程序博客网 时间:2024/05/21 22:54

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

Subscribe to see which companies asked this question

class Solution {public:int evalRPN(vector<string>& tokens) {stack<int> stk;for (string str : tokens){if (!isOp(str)){stk.push(stoi(str));}else{int num1 = stk.top(); stk.pop();int num2 = stk.top(); stk.pop();int num=0;switch (str[0]){case '+':num = num1 + num2; break;case '-':num = num2 - num1; break;case '*':num = num1*num2; break;case '/':num = num2 / num1; break;default:break;}stk.push(num);}}return stk.top();}private:bool isOp(string str){if (str.size()==1&&(str[0] == '+' || str[0] == '-' ||str[0] == '*' || str[0] == '/')){return true;}return false;}};


0 0
原创粉丝点击