150. Evaluate Reverse Polish Notation
来源:互联网 发布:软件界面显示不全 编辑:程序博客网 时间:2024/06/03 13:20
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用stack解题。遍历字符串数组,如果是符号,从stack里弹出两个数进行对应的计算,如果是数字,转化成对应值之后入栈,最后结果返回stack的仅存的一个数。代码如下:
public class Solution { public int evalRPN(String[] tokens) { if(tokens.length == 0) { return 0; } Stack<Integer> stack = new Stack<Integer>(); int num1 = 0, num2 = 0; for (String str: tokens) { if (str.equals("+")) { num2 = stack.pop(); num1 = stack.pop(); stack.push(num1 + num2); } else if (str.equals("-")) { num2 = stack.pop(); num1 = stack.pop(); stack.push(num1 - num2); } else if (str.equals("*")) { num2 = stack.pop(); num1 = stack.pop(); stack.push(num1 * num2); } else if (str.equals("/")) { num2 = stack.pop(); num1 = stack.pop(); stack.push(num1 / num2); } else { stack.push(Integer.parseInt(str)); } } return stack.pop(); }}
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
- <基础原理进阶>机器学习算法python实现【0】回归简谈&三种梯度下降算法
- Struts2_介绍struts2及struts2开发环境的搭建
- 数字滤波算法
- 争做“丝路精神“的现代传人,学习”丝路精神“的感悟
- CS学习资源推荐(持续更新)
- 150. Evaluate Reverse Polish Notation
- 计算机组成原理课本的问题总结
- Python语言中文件的基本处理--Python(19)
- Json的认识
- 转换成3NF的保持无损连接和函数依赖的分解
- 免费的论文查重网站
- 转换成BCNF的保持无损连接的分解
- Redis常用命令-键值相关命令
- Mybatis配置之<objectFactory>元素详述