File tree 2 files changed +46
-0
lines changed
2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 198
198
219|[ Contains Duplicate II] ( ./0219-contains-duplicate-ii.js ) |Easy|
199
199
220|[ Contains Duplicate III] ( ./0220-contains-duplicate-iii.js ) |Hard|
200
200
222|[ Count Complete Tree Nodes] ( ./0222-count-complete-tree-nodes.js ) |Easy|
201
+ 224|[ Basic Calculator] ( ./0224-basic-calculator.js ) |Hard|
201
202
225|[ Implement Stack using Queues] ( ./0225-implement-stack-using-queues.js ) |Easy|
202
203
226|[ Invert Binary Tree] ( ./0226-invert-binary-tree.js ) |Easy|
203
204
228|[ Summary Ranges] ( ./0228-summary-ranges.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 224. Basic Calculator
3
+ * https://leetcode.com/problems/basic-calculator/
4
+ * Difficulty: Hard
5
+ *
6
+ * Given a string s representing a valid expression, implement a basic calculator to
7
+ * evaluate it, and return the result of the evaluation.
8
+ *
9
+ * Note: You are not allowed to use any built-in function which evaluates strings as
10
+ * mathematical expressions, such as eval().
11
+ */
12
+
13
+ /**
14
+ * @param {string } s
15
+ * @return {number }
16
+ */
17
+ var calculate = function ( s ) {
18
+ const stack = [ ] ;
19
+ let result = 0 ;
20
+
21
+ for ( let i = 0 , sign = 1 ; i < s . length ; i += 1 ) {
22
+ if ( s [ i ] >= '0' && s [ i ] <= '9' ) {
23
+ let value = 0 ;
24
+ while ( s [ i ] >= '0' && s [ i ] <= '9' ) {
25
+ value = ( value * 10 ) + ( s [ i ] - '0' ) ;
26
+ i += 1 ;
27
+ }
28
+ result += value * sign ;
29
+ i -= 1 ;
30
+ } else if ( s [ i ] === '+' ) {
31
+ sign = 1 ;
32
+ } else if ( s [ i ] === '-' ) {
33
+ sign = - 1 ;
34
+ } else if ( s [ i ] === '(' ) {
35
+ stack . push ( result , sign ) ;
36
+ result = 0 ;
37
+ sign = 1 ;
38
+ } else if ( s [ i ] === ')' ) {
39
+ result = stack . pop ( ) * result ;
40
+ result += stack . pop ( ) ;
41
+ }
42
+ }
43
+
44
+ return result ;
45
+ } ;
You can’t perform that action at this time.
0 commit comments