题解 | #逆波兰表达式求值#

逆波兰表达式求值

https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param tokens string字符串一维数组 
# @return int整型
#
class Solution:
    def evalRPN(self , tokens: List[str]) -> int:
        #2+1=3  3*4=12
        # write code here
        list1=[]
        for char in tokens:
            if char in '+-*/':
                a=list1.pop()
                b=list1.pop()
                if char=='+':
                    list1.append(a+b)
                elif char=='-':
                    list1.append(b-a)
                elif char=='*':
                    list1.append(a*b)
                else:
                    list1.append(int(b/a))
            else:
                list1.append(int(char))
        return list1[0]                            
        # list1=[]
        # for char in tokens:
        #     if char=='+'and len(list1)>=2:
        #         a=list1.pop()
        #         b=list1.pop()
        #         result=a+b
        #         list1.append(result)
        #     elif char=='-' and len(list1)>=2:
        #         a=list1.pop()
        #         b=list1.pop()
        #         result=b-a
        #         list1.append(result)
        #     elif char=='*'and len(list1)>=2:
        #         a=list1.pop()
        #         b=list1.pop()
        #         result=a*b
        #         list1.append(result)
        #     elif char=='/' and len(list1)>=2:
        #         a=list1.pop()
        #         b=list1.pop()
        #         result=a/b
        #         list1.append(result)
        #     else:
        #         list1.append(int(char))    
        # return list1[0]                      


全部评论

相关推荐

06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务