File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -77,3 +77,49 @@ const calculate = function(s) {
7777
7878 return res + op * num
7979} ;
80+
81+ // another
82+ /**
83+ * @param {string } s
84+ * @return {number }
85+ */
86+ const calculate = function ( s ) {
87+ s = s . trim ( )
88+
89+ let res = 0 , num = 0 , op = 1
90+ const isDigit = ch => ch >= '0' && ch <= '9'
91+ const stk = [ ]
92+ for ( let i = 0 , n = s . length ; i < n ; i ++ ) {
93+
94+ const e = s [ i ]
95+ if ( e === ' ' ) continue
96+ if ( isDigit ( e ) ) num = num * 10 + ( + e )
97+ else {
98+
99+ if ( e === '(' ) {
100+ stk . push ( res )
101+ stk . push ( op )
102+
103+ res = 0
104+ num = 0
105+ op = 1
106+ } else if ( e === ')' ) {
107+ res += num * op
108+ res *= stk . pop ( )
109+ res += stk . pop ( )
110+ op = 1
111+ num = 0
112+ } else if ( e === '-' ) {
113+ res += num * op
114+ op = - 1
115+ num = 0
116+ } else if ( e === '+' ) {
117+ res += num * op
118+ op = 1
119+ num = 0
120+ }
121+ }
122+ }
123+
124+ return res + num * op
125+ } ;
You can’t perform that action at this time.
0 commit comments