逆波兰表达式, 设置 stack 遍历表达式中的数据,当遇到加减乘除时, 弹出 stack 栈顶元素,进行计算操作, 注意 减法 和 除法时, 减数和除数是栈顶元素
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param tokens string字符串一维数组
# @return int整型
#
class Solution:
def evalRPN(self , tokens: List[str]) -> int:
# write code here
stack = []
for t in tokens:
if t not in "+-*/":
if t[0] == "-":
stack.append(0-int(t[1:]))
else:
stack.append(int(t))
else:
b, a = stack.pop(), stack.pop()
if t == "+":
stack.append(a + b)
elif t == "-":
stack.append(a - b)
elif t == "*":
stack.append(a * b)
elif t == "/":
if a < 0 or b < 0:
stack.append(int(a / b))
else:
stack.append(a // b)
return stack[0]