# LeetCode——Evaluate Reverse Polish Notation

170人阅读 评论(0)

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

class Solution {
public:
int calcWithOperator(const string& op, int l, int r) {
char c = *op.c_str();
switch (c) {
case '+':
return l + r;
case '-':
return l - r;
case '*':
return l * r;
case '/':
return l / r;
}
return 0;
}

bool isStringOperator(const string& str) {
if (str.length() != 1) {
return false;
}

char c = *str.c_str();
return c == '+' || c == '-' || c == '*' || c == '/';
}

int evalRPN(vector<string>& tokens) {
stack<int> stackNum;

for (int i = 0; i != tokens.size(); ++i) {
const string str = tokens[i];
if (isStringOperator(str)) {
if (stackNum.size() < 2) {
return -1;
} else {
int r = stackNum.top();
stackNum.pop();
int l = stackNum.top();
stackNum.pop();
int result = calcWithOperator(str, l, r);
stackNum.push(result);
}
} else {
stackNum.push(atoi(str.c_str()));
}
}

if (stackNum.size() != 1) {
return -1;
} else {
return stackNum.top();
}
}
};
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：24787次
• 积分：837
• 等级：
• 排名：千里之外
• 原创：48篇
• 转载：7篇
• 译文：0篇
• 评论：2条
评论排行
最新评论