Evaluate Reverse Polish Notation

Problem: Evaluate Reverse Polish Notation

The general idea is to push un-operated numbers into a stack and when we have a operator pop our two operands and push the result back in.

Code in Python:

class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        operands = []
        for s in tokens:
            if s == "+":
                x = operands.pop()
                y = operands.pop()
                operands.append(y+x)
            elif s == "-":
                x = operands.pop()
                y = operands.pop()
                operands.append(y-x)
            elif s == "*":
                x = operands.pop()
                y = operands.pop()
                operands.append(y*x)
            elif s == "/":
                x = operands.pop()
                y = operands.pop()
                if y * x < 0 and y % x != 0:
                    operands.append(y/x+1)
                else:
                    operands.append(y/x)
            else:
                operands.append(int(s))

        return operands[0]

results matching ""

    No results matching ""