150. Evaluate Reverse Polish Notation
来源:互联网 发布:软件著作权 开源代码 编辑:程序博客网 时间:2024/05/18 00:49
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
import java.util.Stack;public class Solution { public int evalRPN(String[] tokens) { int rst = 0; Stack<String> stack = new Stack<String>(); for(String s : tokens) { if("+".equals(s)) { int a = Integer.parseInt(stack.pop()), b = Integer.parseInt(stack.pop()); rst = a + b; stack.push(rst + ""); } else if("-".equals(s)) { int a = Integer.parseInt(stack.pop()), b = Integer.parseInt(stack.pop()); rst = b - a; stack.push(rst + ""); } else if("*".equals(s)) { int a = Integer.parseInt(stack.pop()), b = Integer.parseInt(stack.pop()); rst = a * b; stack.push(rst + ""); } else if("/".equals(s)) { int a = Integer.parseInt(stack.pop()), b = Integer.parseInt(stack.pop()); rst = b / a; stack.push(rst + ""); } else { rst = Integer.parseInt(s); stack.push(s); } } return rst; }}
0 0
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 函数变相做到返回多个值的方法
- 原币金额与本币金额的区别
- 约瑟夫环问题
- GOF设计模式之STRATEGY(策略)
- 用函数实现strcmp
- 150. Evaluate Reverse Polish Notation
- 简单化搭建 Docker 数据中心
- python+selenium(环境的安装)
- 读者写者算法
- 16哈理工新生赛 E Nine Digits (BFS+康拓展开)
- 2048(游戏)
- 初识面向对象
- Linux编译内核(4.2.6)并添加系统调用
- 十一个顶级的Git 客户端,绝对很实用!