Evaluate Reverse Polish Notation
2015-11-04 18:03
295 查看
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:
关键点:stack
思路:遇到数字则进栈,遇到操作符则取出栈顶的两个元素进行运算,要注意的是取出的元素和操作数顺序的关系。
代码:
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
switch (tokens[i]) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
stack.push(-stack.pop() + stack.pop());
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
int n1 = stack.pop(), n2 = stack.pop();
stack.push(n2 / n1);
break;
default:
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}
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
关键点:stack
思路:遇到数字则进栈,遇到操作符则取出栈顶的两个元素进行运算,要注意的是取出的元素和操作数顺序的关系。
代码:
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
switch (tokens[i]) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
stack.push(-stack.pop() + stack.pop());
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
int n1 = stack.pop(), n2 = stack.pop();
stack.push(n2 / n1);
break;
default:
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}
相关文章推荐
- 关于 lua的常用 语句 比较实用
- skynet的定时器
- Lua1.1 Lua 的设计和实现 (二)
- Lua1.1 Lua 的设计和实现 (一)
- Lua1.1 公开发布的第一版
- Lua 单例
- Lua1.0 代码分析 库
- Lua1.0 代码分析 opcode.c
- lua中A文件调用B文件中函数的方法
- 利用openresty-lua生态修改upstream后端服务
- Lua1.0 代码分析 hash.c
- Lua 类的继承与函数override
- lua几点注意和脚本操作gui文件
- Lua1.0 代码分析 table.c
- Lua1.0 代码分析 inout.c
- lua的table库中的常用函数总结
- Lua 中实现类
- lua 字符串处理
- ZeroBrane Studio远程调试Lua程序
- lua语言中transpose()函数的用法