File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string } s
3+ * @return {number }
4+ */
5+ var calculate = function ( s ) {
6+ let res = 0 ;
7+ let num = 0 ;
8+ let sign = 1 ;
9+ const stack = [ ] ;
10+
11+ for ( let i = 0 ; i < s . length ; i ++ ) {
12+ const ch = s [ i ] ;
13+
14+ if ( ch >= "0" && ch <= "9" ) {
15+ num = num * 10 + ( ch . charCodeAt ( 0 ) - 48 ) ;
16+ } else if ( ch === "+" ) {
17+ res += sign * num ;
18+ num = 0 ;
19+ sign = 1 ;
20+ } else if ( ch === "-" ) {
21+ res += sign * num ;
22+ num = 0 ;
23+ sign = - 1 ;
24+ } else if ( ch === "(" ) {
25+ stack . push ( res ) ;
26+ stack . push ( sign ) ;
27+ res = 0 ;
28+ num = 0 ;
29+ sign = 1 ;
30+ } else if ( ch === ")" ) {
31+ res += sign * num ;
32+ num = 0 ;
33+
34+ const prevSign = stack . pop ( ) ;
35+ const prevRes = stack . pop ( ) ;
36+
37+ res = prevRes + prevSign * res ;
38+ }
39+ }
40+ return res + sign * num ;
41+ } ;
You can’t perform that action at this time.
0 commit comments