evaluate-reverse-polist-notation leetcode C++

mac2022-06-30  81

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

C++

class Solution { public: int evalRPN(vector<string> &tokens){ int len = tokens.size(); stack<int> S; for (int i = 0; i< len; i++){ if ("+" == tokens[i] || "-" == tokens[i] || tokens[i] == "*" || tokens[i] == "/"){ int arg2 = S.top(); S.pop(); int arg1 = S.top(); S.pop(); S.push(runOperator(arg1,arg2,tokens[i][0])); }else S.push(stoi(tokens[i])); } return S.top(); } int runOperator(int arg1,int arg2,char optor){ if('+' == optor) return arg1 + arg2; else if('-' == optor) return arg1 - arg2; else if('*' == optor) return arg1 * arg2; else return arg1 / arg2; } };

 

转载于:https://www.cnblogs.com/vercont/p/10210284.html

最新回复(0)