题目链接: Evaluate Reverse Polish Notation
题目意思: 给的一个表达式,求值
代码:
class Solution { public: bool IsOperator(const string &str); int GetStackTop(stack<int> &stack); int evalRPN(vector<string> &tokens); }; bool Solution::IsOperator(const string &str) { if (str == "+" || str == "-" || str == "*" || str == "/") { return true; } return false; } int Solution::GetStackTop(stack<int> &stack) { if (stack.empty()) { throw "stack is empty"; return -1; } int topValue = stack.top(); stack.pop(); return topValue; } int Solution::evalRPN(vector<string> &tokens) { stack <int> number; int tokensSize = tokens.size(); for (int i = 0; i < tokensSize; ++i) { if (IsOperator(tokens[i])) { int rightNumber = GetStackTop(number); int leftNumber = GetStackTop(number); int result = 0; if (tokens[i] == "+") { result = leftNumber + rightNumber; } else if (tokens[i] == "-") { result = leftNumber - rightNumber; } else if (tokens[i] == "*") { result = leftNumber * rightNumber; } else { result = leftNumber / rightNumber; } number.push(result); } else { number.push(atoi(tokens[i].c_str())); } } return GetStackTop(number); }
时间: 2024-11-10 12:02:21