leetcode--Evaluate Reverse Polish Notation
2015-06-19 23:04
316 查看
Evaluate the value of an arithmetic expression in
Reverse Polish Notation.
Valid operators are
Some examples:
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
public class Solution { public int evalRPN(String[] tokens) { Stack<String> stack = new Stack<String>(); int num1 = 0; int num2 = 0; for(int i=0;i<tokens.length;i++){ switch (tokens[i]) { case "+": num1 = Integer.valueOf(stack.pop()); num2 = Integer.valueOf(stack.pop()); stack.add((num2+num1)+""); break; case "-": num1 = Integer.valueOf(stack.pop()); num2 = Integer.valueOf(stack.pop()); stack.add((num2-num1)+""); break; case "*": num1 = Integer.valueOf(stack.pop()); num2 = Integer.valueOf(stack.pop()); stack.add((num2*num1)+""); break; case "/": num1 = Integer.valueOf(stack.pop()); num2 = Integer.valueOf(stack.pop()); stack.add((num2/num1)+""); break; default: stack.add(tokens[i]); break; } } return Integer.valueOf(stack.pop()); } }
相关文章推荐
- LeetCode 之 Evaluate Reverse Polish Notation — C++ 实现
- 编译 lua cjson模块
- lua学习笔记_注释、基本数据类型、if语句
- lua学习1
- lua (一) : mac终端下使用 brew安装lua
- 自学Lua(2)--Lua表达式
- 自学Lua(1)--Lua语法特点
- 4.Lua面向对象概念
- 3.Lua表和数组
- lua 获取指定目录下指定后缀文件名
- 我所理解lua 语言中的点、冒号与self
- 1.Lua 环境搭建
- lua文件读写
- Lua lib 加载分析
- Virtual View Synthesis Method and Self Evaluation Metrics for Free Viewpoint Television and 3D Video
- Lua 学习笔记四 CoronaSDK使用
- Lua之sethook学习
- Lua之pcall和xpcall之学习
- Lua如何设置局部变量值进行调试
- VC中出现error C2064: term does not evaluate to a function