您的位置:首页 > 编程语言 > Lua

Evaluate Reverse Polish Notation

2015-06-03 21:05 393 查看
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:
bool notOperator(string ch) {
return ch != "+" && ch != "-" && ch != "*" && ch != "/";
}

int evalRPN(vector<string>& tokens) {
stack<int> operands;
int ans;
for (int i = 0; i < tokens.size(); i++) {
if (notOperator(tokens[i]))
operands.push(atoi(tokens[i].c_str()));
else {
int operand2 = operands.top();
operands.pop();
int operand1 = operands.top();
operands.pop();
if (tokens[i] == "+")
ans = operand1 + operand2;
else if (tokens[i] == "-")
ans = operand1 - operand2;
else if (tokens[i] == "*")
ans = operand1 * operand2;
else
ans = operand1 / operand2;
operands.push(ans);
}
}
return operands.top();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: