Python Solution


  • 0
    S
    class Solution(object):
        def evalRPN(self, tokens):
            """
            :type tokens: List[str]
            :rtype: int
            """
            stack = []
            for token in tokens:
                if token != "+" and token != "-" and token != "*" and token != "/":
                    stack.append(int(token))
                else:
                    a = stack.pop()
                    b = stack.pop()
                    if token == "+":
                        stack.append(a + b)
                    elif token == "-":
                        stack.append(b - a)
                    elif token == "*":
                        stack.append(a * b)
                    elif token == "/":
                        if a*b < 0:
                            stack.append(-(abs(b)/abs(a)))
                        else:
                            stack.append(b / a)
                
            return stack[-1]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.