150. Evaluate Reverse Polish Notation

https://leetcode.com/problems/evaluate-reverse-polish-notation/

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        ops = "+-*/"
        for token in tokens:
            if token in ops:
                num2=stack.pop()
                num1 = stack.pop()
                curr=0
                if token =="/":
                    l = int(num1)
                    r = int(num2)
                    if l*r < 0 and l % r != 0:
                        stack.append(str(l//r+1))
                    else:
                        stack.append(str(l//r))
                else:
                    curr = eval(num1+token+num2)
                    stack.append(str(curr))
            else:
                stack.append(token)
        return int(stack[0])
            
        

Last updated

Was this helpful?