-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05_BasicCalculator.py
More file actions
38 lines (31 loc) · 1.15 KB
/
05_BasicCalculator.py
File metadata and controls
38 lines (31 loc) · 1.15 KB
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
# Question link - https://leetcode.com/problems/basic-calculator/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def calculate(self, s: str) -> int:
# Initalize the curr and res
curr = res = 0
# Define sign initially +ve as 1
sign = 1
# Define stack for saving the state
stack = []
for char in s:
# If it is digit
if char.isdigit():
# Process the digit but it can be 22 , 333
curr = curr * 10 + int(char)
elif char in ["+" , "-"]:
res += sign * curr
sign = 1 if char == "+" else -1
curr = 0
elif char == "(":
stack.append(res)
stack.append(sign)
sign = 1
res = 0
elif char == ")":
res += sign * curr
res *= stack.pop()
res += stack.pop()
curr = 0
# Just ignore the " " conditon for the else case
# And if any char left , then calcuate te res = res + sign * curr
return res + sign * curr