File tree 2 files changed +38
-0
lines changed 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 227. Basic Calculator II
3
+ * https://leetcode.com/problems/basic-calculator-ii/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given a string s which represents an expression, evaluate this expression and return its value.
7
+ *
8
+ * The integer division should truncate toward zero.
9
+ *
10
+ * You may assume that the given expression is always valid. All intermediate results will be in
11
+ * the range of [-231, 231 - 1].
12
+ *
13
+ * Note: You are not allowed to use any built-in function which evaluates strings as mathematical
14
+ * expressions, such as eval().
15
+ */
16
+
17
+ /**
18
+ * @param {string } s
19
+ * @return {number }
20
+ */
21
+ var calculate = function ( s ) {
22
+ const stack = [ ] ;
23
+
24
+ for ( let i = 0 , num = 0 , sign = '+' ; i < s . length ; i ++ ) {
25
+ if ( s [ i ] >= '0' && s [ i ] <= '9' ) num = num * 10 + ( s [ i ] - '0' ) ;
26
+ if ( ( s [ i ] < '0' && s [ i ] !== ' ' ) || i === s . length - 1 ) {
27
+ if ( sign === '+' ) stack . push ( num ) ;
28
+ else if ( sign === '-' ) stack . push ( - num ) ;
29
+ else if ( sign === '*' ) stack . push ( stack . pop ( ) * num ) ;
30
+ else if ( sign === '/' ) stack . push ( Math . trunc ( stack . pop ( ) / num ) ) ;
31
+ sign = s [ i ] ;
32
+ num = 0 ;
33
+ }
34
+ }
35
+
36
+ return stack . reduce ( ( a , b ) => a + b , 0 ) ;
37
+ } ;
Original file line number Diff line number Diff line change 208
208
224|[ Basic Calculator] ( ./0224-basic-calculator.js ) |Hard|
209
209
225|[ Implement Stack using Queues] ( ./0225-implement-stack-using-queues.js ) |Easy|
210
210
226|[ Invert Binary Tree] ( ./0226-invert-binary-tree.js ) |Easy|
211
+ 227|[ Basic Calculator II] ( ./0227-basic-calculator-ii.js ) |Medium|
211
212
228|[ Summary Ranges] ( ./0228-summary-ranges.js ) |Easy|
212
213
229|[ Majority Element II] ( ./0229-majority-element-ii.js ) |Medium|
213
214
230|[ Kth Smallest Element in a BST] ( ./0230-kth-smallest-element-in-a-bst.js ) |Medium|
You can’t perform that action at this time.
0 commit comments