Time:2019/4/14
Title: Evaluate Reverse Polish Notation
Difficulty: Medium
Author:小鹿javascript
Evaluate the value of an arithmetic expression in Reverse Polish Notation.java
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.git
Note:github
根据逆波兰表示法,求表达式的值。算法
有效的运算符包括
+
,-
,*
,/
。每一个运算对象能够是整数,也能够是另外一个逆波兰表达式。express说明:数组
- 整数除法只保留整数部分。
- 给定逆波兰表达式老是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的状况。
Example 1:ide
Input: ["2", "1", "+", "3", "*"] Output: 9 Explanation: ((2 + 1) * 3) = 9
Example 2:lua
Input: ["4", "13", "5", "/", "+"] Output: 6 Explanation: (4 + (13 / 5)) = 6
Example 3:code
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22
仔细观察上述的逆波兰表达式,能够发现一个规律就是每遇到一个操做符,就将操做符前的两个操做数进行运算,将结果保存到原位置。1)咱们能够将这个过程用栈来进行操做。
2)全部的操做数都执行近栈操做,当遇到操做符时,在栈中取出两个操做数进行计算,而后再将其压入栈内,继续遍历数组元素,直到遍历完整个数组为止。
3)到最后,栈内只剩下一个数,那就是最后的结果。
虽然过程很好理解,代码写起来很简单,可是想把算法写的全面仍是须要考虑到不少方面的。1)数组中的是字符串类型,要进行数据类型转换
parseInt()
。2)两个操做数进行运算时,第二个出栈的操做数在前,第一个出栈的操做数在后(注意除法)。
3)对于浮点型数据,只取小数点以前的整数。
4)关于负的浮点型(尤为是 0 点几 ),要取 0 绝对值 0 ,或直接转化为整数。
var evalRPN = function(tokens) { // 声明栈 let stack = []; for(let item of tokens){ switch(item){ case '+': let a1 = stack.pop(); let b1 = stack.pop(); stack.push(b1 + a1); break; case '-': let a2 = stack.pop(); let b2 = stack.pop(); stack.push(b2 - a2); break; case '*': let a3 = stack.pop(); let b3 = stack.pop(); stack.push(b3 * a3); break; case '/': let a4 = stack.pop(); let b4 = stack.pop(); stack.push(parseInt(b4 / a4)); break; default: stack.push(parseInt(item)); } } return parseInt(stack.pop()); };
欢迎一块儿加入到 LeetCode 开源 Github 仓库,能够向 me 提交您其余语言的代码。在仓库上坚持和小伙伴们一块儿打卡,共同完善咱们的开源小仓库!
Github:https://github.com/luxiangqia...