File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ # time complexity: O(n)
2+ # space complexity: O(n)
3+ import math
4+
5+
6+ class Solution :
7+ def calculate (self , s : str ) -> int :
8+ num = 0
9+ prevOperation = '+'
10+ s += '+'
11+ stack = []
12+ for c in s :
13+ if c .isdigit ():
14+ num = num * 10 + int (c )
15+ elif c == ' ' :
16+ pass
17+ else :
18+ if prevOperation == '+' :
19+ stack .append (num )
20+ elif prevOperation == '-' :
21+ stack .append (- num )
22+ elif prevOperation == '*' :
23+ operant = stack .pop ()
24+ stack .append ((operant * num ))
25+ elif prevOperation == '/' :
26+ operant = stack .pop ()
27+ stack .append (math .trunc (operant / num ))
28+ num = 0
29+ prevOperation = c
30+ return sum (stack )
31+
32+
33+ s = "3+2*2"
34+ print (Solution ().calculate (s ))
35+ s = " 3/2 "
36+ print (Solution ().calculate (s ))
37+ s = " 3+5 / 2 "
38+ print (Solution ().calculate (s ))
You can’t perform that action at this time.
0 commit comments