题目

根据逆波兰表达式,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:

  • 整数除法只保留整数部分。
  • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

image.png

思路

  1. class Solution:
  2. def evalRPN(self, tokens: List[str]) -> int:
  3. operators = '+-*/'
  4. stack = []
  5. for ch in tokens:
  6. if ch not in operators:
  7. stack.append(ch)
  8. else:
  9. num1 = stack.pop()
  10. num2 = stack.pop()
  11. cal = str(int(eval(num2 + ch + num1)))
  12. stack.append(cal)
  13. return int(stack[0])