Calculator
772. Basic Calculator III
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
Operand has 2 level priority
l2 prior than l1, o1 denotes (+, -), o2 denotes (*, /)
sign can happen in the beginning of string
Conditions
1 Numbers: get the number, update l2 and sign
2 (*, /) operator: update o2
3 (+, /) operator: update l1, o1, reset l2, o2
4 '(': Use recursion to find num and update l2
Hint: ignore ')'
final return
l1 + o1*l2
Recursion
def calculate(self, s: str) -> int:
s.replace(' ', '')
l1, o1 = 0, 1
l2, o2 = 1, 1
sign = 0
i = 0
if s[0] in ('+', '-'):
sign = 1 if s[0] == '+' else -1
i+=1
# must ignore ')'
while i < len(s):
c = s[i]
if c.isdigit():
num = int(c)
while i+1 < len(s) and s[i+1].isdigit():
num = num*10 + int(s[i+1])
i+=1
if sign:
num *= sign
l2 = l2*num if o2 else int(l2/num)
sign = 0
elif c == '(':
count = 0
start = i
while i < len(s):
if s[i] == '(': count+=1
if s[i] == ')': count-=1
if count == 0: break
i+=1
num = self.calculate(s[start+1:i])
l2 = l2*num if o2 else int(l2/num)
elif c in ('*', '/'):
o2 = 1 if c == '*' else 0
elif c in ('+', '-'):
l1 = l1 + o1*l2
o1 = 1 if c == '+' else -1
l2, o2 = 1, 1
i+=1
return l1 + o1*l2 Stack
224. Basic Calculator I
+, - , (, )
Stack
227. Calculator II
+, - *, /
Last updated
Was this helpful?