Calculator

Catalogue
  1. 1. 150. Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation

  • Stack, Reverse Polish Notation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
def evalRPN(self, tokens):
stack = []
for token in tokens:
if token in "+-*/":
n2 = stack.pop()
n1 = stack.pop()
if token == '+':
temp = n1 + n2
elif token == '-':
temp = n1 - n2
elif token == '*':
temp = n1 * n2
else:
temp = n1 / n2
if n1 * n2 < 0 and n1 % n2 != 0:
temp += 1
stack.append(temp)
else:
stack.append(int(token))
return stack.pop()
Share