File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change @@ -30,6 +30,7 @@ since 2021.10.10 / Benben
30
30
- 0035.Search Insert Position
31
31
- 0053.Maximum SubArray
32
32
- 0058.Length of Last Word
33
+ - 0067.Add Binary
33
34
- 0104.Maximum Depth of Binary Tree
34
35
- 0100.Same Tree
35
36
- 0110.Balanced Binary Tree
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } a
3
+ * @param {string } b
4
+ * @return {string }
5
+ */
6
+ var addBinary = function ( a , b ) {
7
+ if ( a . length < b . length ) return addBinary ( b , a )
8
+ const arrA = a . split ( '' ) . reverse ( )
9
+ const arrB = b . split ( '' ) . reverse ( )
10
+ let curry = 0
11
+ let sum = 0
12
+
13
+ arrA . forEach ( ( e , i ) => {
14
+ let numB = 0
15
+ if ( i < arrB . length ) numB = + ( arrB [ i ] )
16
+ sum = curry + ( + e ) + numB
17
+ switch ( sum ) {
18
+ case 0 :
19
+ arrA [ i ] = '0'
20
+ curry = 0
21
+ break
22
+ case 1 :
23
+ arrA [ i ] = '1'
24
+ curry = 0
25
+ break
26
+ case 2 :
27
+ arrA [ i ] = '0'
28
+ curry = 1
29
+ break
30
+ case 3 :
31
+ arrA [ i ] = '1'
32
+ curry = 1
33
+ break
34
+ }
35
+ } )
36
+
37
+ if ( curry ) arrA . push ( '1' )
38
+ return arrA . reverse ( ) . join ( '' )
39
+ } ;
40
+
41
+ // 2022/06/13 done.
42
+ // Runtime: 105 ms, faster than 28.95% of JavaScript online submissions for Add Binary.
43
+ // Memory Usage: 42.6 MB, less than 80.31% of JavaScript online submissions for Add Binary.
You can’t perform that action at this time.
0 commit comments