题解 | #逆波兰表达式求值#
逆波兰表达式求值
https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param tokens string字符串一维数组
# @return int整型
#
class Solution:
def evalRPN(self , tokens: List[str]) -> int:
# write code here
stack = []
for i in tokens:
if i not in "+-*/":
if i[0] == "-":
b = i[1:]
stack.append(0-int(b))
else:
stack.append(int(i))
else:
if i == "+":
b, a= stack.pop(),stack.pop()
stack.append(a+b)
if i == "-":
b, a= stack.pop(),stack.pop()
stack.append(a-b)
if i == "*":
b, a= stack.pop(),stack.pop()
stack.append(a*b)
if i == "/":
b, a= stack.pop(),stack.pop()
stack.append(int(a/b))
return stack[0]
int(a/b) 这个是向0靠近 例如int(-5/2)=-2
a//b 这个是向下取整 floor函数 (-5//2)=-3
这两个函数在大于0的时候是一样的作用,但是小于0的时候是不一样的
查看20道真题和解析