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:
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();
}
};
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();
}
};
相关文章推荐
- Mac 使用 ZeroBrane Studio 开发lua
- Lua查找表元素过程(元表、__index方法是如何工作的)
- Lua常用的4中遍历方式
- LUA中遇到这个错误attempt to call a nil value (global 'loadstring')
- 汉罗塔lua实现
- 在 slua 中使用更新的面向对象方案
- lua-5.1 和 lua-5.2 之间的一些差异。
- LUA modue require package 区别
- c++下 遍历 lua table
- SLua 中继承 C# 类接口 Slua.Class 的一个 Bug。
- ALUA的Path Selection Policy选择
- wxLua 如何打包生成可执行文件
- 绑定自定义类到lua
- lua 学习笔记 三 & 四
- 初学lua的几个博客 挺好的
- C++调用Lua读取配置文件的一个简单例子
- Lua中的线程和状态
- lua路上踩到的坑
- Lua 的模块安装和部署工具 - LuaRocks
- LuaSocket