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
Code:
class Solution { public: bool isOperator(string op){ return (op=="+"||op=="-"||op=="*"||op=="/"); } int calculate(int operand1, int operand2, string op){ if(op=="+") return operand1+operand2; else if(op=="-") return operand1-operand2; else if(op=="*") return operand1*operand2; else return operand1/operand2; } int evalRPN(vector<string> &tokens) { if(tokens.empty()) return 0; stack<int> store; for(int i=0; i<tokens.size(); i++){ if(isOperator(tokens[i])){ int operand2 = store.top(); store.pop(); int operand1 = store.top(); store.pop(); store.push(calculate(operand1, operand2, tokens[i])); } else store.push(stoi(tokens[i])); } return store.top(); } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步