[LC] 150. Evaluate Reverse Polish Notation
2024-09-07 06:36:30
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Note:
- Division between two integers should truncate toward zero.
- The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
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
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
import string
nums = string.digits
operator = ['+', '-', '*', '/'] for token in tokens:
if token in operator:
last_one = stack.pop()
last_two = stack.pop()
cur_val = self.helper(last_one, last_two, token)
stack.append(cur_val)
else:
stack.append(int(token))
return stack.pop() def helper(self, last_one, last_two, operator):
if operator == '+':
return last_two + last_one
elif operator == '-':
return last_two - last_one
elif operator == '*':
return last_two * last_one
elif operator == '/':
# special case to get ceiling value
if last_two * last_one < 0 and last_two % last_one != 0:
return last_two // last_one + 1
else:
return last_two // last_one
else:
return
最新文章
- T-SQL 将存储过程结果插入到表中
- 国内其他的maven库
- 关于MVC4项目从32位机移到64位机编译报错解决方案
- performSelector的原理以及用法
- mac 下 终端常用命令
- 一个响应式数据库框架SQLBrite,完美解决数据库和UI的同步更新!
- Python设计模式——外观模式
- 你好,C++(16)用表达式表达我们的设计意图——4.1 用操作符对数据进行运算
- Delphi IDHTTP用法详解(六种用法)
- springmvc 之 深入核心研究
- Junit4学习(六)Junit4参数化设置
- 实用的shell脚本面试题和答案
- java打印系统时间
- 2017-12-15python全栈9期第二天第三节之使用while循环输出1到100的奇数,
- MySQL数据库基本命令-1
- 【转】scapy 构造以太网注入帧
- textInput事件
- Python 程序员都会喜欢的 6 个库
- C#拖拽操作
- php -- PHP在linux上执行外部命令,system(),exec(),shell_exec()