https://leetcode.com/problems/evaluate-reverse-polish-notation/
题目描述
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.
解题思路
因为早出现的数字反而越靠后参与运算, 很容易想到用stack, 遍历tokens, 每次遇到数字, 进行入栈操作. 遇到运算符的时候, 弹出两个栈顶元素运算, 将结果入栈.
**本题唯一要注意的是:**当两个符号相反的数且不能整除的数相除的时候, 代码的得出的结果要+1. 例如 3/-2=-2, -4/3=-2, 它是会向下取整的. 因此要+1才等于真实结果. 如果能整除, 4/-2=-2, 则不能+1.
代码
class Solution:
def evalRPN(self, tokens):
if len(tokens) == 0:
return 0
if len(tokens) == 1:
return tokens[0]
stack = []
# 根据四种运算符,分四种情况讨论
for token in tokens:
if token == '+':
res = 0
res += stack.pop()
res += stack.pop()
stack.append(res)
elif token == '-':
res = 0
res -= stack.pop()
res += stack.pop()
stack.append(res)
elif token == '*':
res = 1
res *= stack.pop()
res *= stack.pop()
stack.append(res)
elif token == '/':
# 如果两数异号且不能整除, 结果需要+1
div = stack.pop()
res = stack.pop()
if div * res < 0 and res % div != 0:
res = res // div + 1
else:
res //= div
stack.append(res)
else:
stack.append(int(token))
return stack[0]