150. Evaluate Reverse Polish Notation
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 55% Topics: Array, Math, Stack
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token.isdigit() or (token[0] == "-" and token[1:].isdigit()):
stack.append(int(token))
else:
num2 = stack.pop()
num1 = stack.pop()
if token == "+":
stack.append(num1 + num2)
elif token == "-":
stack.append(num1 - num2)
elif token == "*":
stack.append(num1 * num2)
elif token == "/":
stack.append(int(num1 / num2))
return stack[0]
Solution from kamyu104/LeetCode-Solutions · MIT
Similar questions