LeetCode-Evaluate Reverse Polish Notation
2015-10-01 08:38
441 查看
因为是很标准的两个oprand 一个operator 所以很简单
但是注意string compare不能用==!!!要用equals
外加注意-和/的顺序
public class Solution {
public int evalRPN(String[] tokens) {
Stack <Integer> stack = new Stack <Integer> ();
for ( int i = 0; i < tokens.length; i ++ ){
if ( tokens[i].equals("+")){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op1 + op2);
}
else if ( tokens[i].equals("-") ){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op2 - op1);
}
else if ( tokens[i].equals("*")){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op1 * op2);
}
else if ( tokens[i].equals("/") ){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op2 / op1);
}
else{
stack.push( Integer.parseInt(tokens[i]));
}
}
return stack.peek();
}
}
但是注意string compare不能用==!!!要用equals
外加注意-和/的顺序
public class Solution {
public int evalRPN(String[] tokens) {
Stack <Integer> stack = new Stack <Integer> ();
for ( int i = 0; i < tokens.length; i ++ ){
if ( tokens[i].equals("+")){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op1 + op2);
}
else if ( tokens[i].equals("-") ){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op2 - op1);
}
else if ( tokens[i].equals("*")){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op1 * op2);
}
else if ( tokens[i].equals("/") ){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op2 / op1);
}
else{
stack.push( Integer.parseInt(tokens[i]));
}
}
return stack.peek();
}
}
相关文章推荐
- lua元表
- Evaluate Reverse Polish Notation
- PB中的Describe,Evaluatate,LookUpDisplay小结
- c++调用lua方法
- c++&lua交互
- 【学习笔记】系列七:Lua 语言 15 分钟快速入门
- 【wireshark】插件开发(四):Lua插件Post-dissector和Listener
- lua的编译、运行
- Evaluate Reverse Polish Notation(堆栈)
- luajit 加密
- 日志Human Resource Evaluation
- Lua程序语言设计学习-0
- windows下使用lua教程(转)
- lua几个易与其他语言(特别C++)混淆的地方
- 玩转lua:搞懂lua潜规则
- 【wireshark】插件开发(三):Lua插件 Dissector
- lua的table.sort 中出现 invalid order function for sorting
- lua - string【方法】
- MonaServer增加luasocket脚本
- lua中的pairs和ipairs