File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -34,3 +34,46 @@ const calculate = function(s) {
34
34
}
35
35
return res + sign * num
36
36
}
37
+
38
+ // another
39
+
40
+ /**
41
+ * @param {string } s
42
+ * @return {number }
43
+ */
44
+ const calculate = function ( s ) {
45
+ s = s . split ( ' ' ) . join ( '' )
46
+ const n = s . length , stack = [ ]
47
+ const isNum = ch => ch >= '0' && ch <= '9'
48
+ let num = 0 , op = 1 , res = 0
49
+ for ( let i = 0 ; i < n ; i ++ ) {
50
+ const ch = s [ i ]
51
+ if ( isNum ( ch ) ) {
52
+ num = num * 10 + ( + ch )
53
+ } else {
54
+ if ( ch === '(' ) {
55
+ stack . push ( res )
56
+ stack . push ( op )
57
+ num = 0
58
+ op = 1
59
+ res = 0
60
+ } else if ( ch === ')' ) {
61
+ res += num * op
62
+ res *= stack . pop ( )
63
+ res += stack . pop ( )
64
+ num = 0
65
+ op = 1
66
+ } else if ( ch === '+' ) {
67
+ res += op * num
68
+ op = 1
69
+ num = 0
70
+ } else if ( ch === '-' ) {
71
+ res += op * num
72
+ op = - 1
73
+ num = 0
74
+ }
75
+ }
76
+ }
77
+
78
+ return res + op * num
79
+ } ;
You can’t perform that action at this time.
0 commit comments