LEETCODE 150. 逆波兰表达式求值

时间:2024-05-06 09:45:50

请添加图片描述

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        # if not tokens:
        #     return -1
        # if len(tokens)==1 and tokens[0].isdigit():
        #     return int(tokens[0])
     
        stack=[]
        for item in tokens:
            if item.isdigit() or item.lstrip('-').isdigit():
                stack.append(int(item))

            elif item in "+-*/":
                n1=stack.pop()
                n2=stack.pop()
                if item=='+':
                    stack.append(n1+n2)
                elif item=='-':
                    stack.append(n2-n1)
                elif item=='*':
                    stack.append(n1*n2)
                elif item=='/':
                    stack.append(int(n2/n1))
        return stack[0]
                


请添加图片描述