-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_calculator.py
46 lines (30 loc) · 1.06 KB
/
basic_calculator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'''
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
'''
class Solution:
def calculate(self, s: str) -> int:
cur = 0
res = 0
sign = 1
stack = []
for ch in s:
if ch.isdigit():
cur = cur*10 + int(ch)
elif ch == ' ':
continue
elif ch in ['+', '-']:
res += sign*cur
sign = 1 if ch == '+' else -1
cur = 0
elif ch == '(':
stack.append(res)
stack.append(sign)
sign = 1
res = 0
elif ch == ')':
res += sign * cur
res *= stack.pop()
res += stack.pop()
cur = 0
return res + sign*cur