2424function binaryGap ( N ) {
2525 // write your code in JavaScript (Node.js 8.9.4)
2626 if ( ! Number ( N ) ) return 0 ;
27+ /*
28+ * This is not optimal
29+ */
2730 // Convert to binary.
28- N = N . toString ( 2 ) ;
29- let a = N . length - 2 ;
30- let b = N . length - 1 ;
31- let arr = N . split ( '' ) ;
32- let spliced ;
33- let isComplete = true ;
34- // Remove zero from the right
35- while ( isComplete ) {
36- if ( arr [ b ] === '1' ) {
37- spliced = arr ;
38- isComplete = false ;
39- break ;
40- }
31+ // N = N.toString(2);
32+ // let a = N.length - 2;
33+ // let b = N.length - 1;
34+ // let arr = N.split('');
35+ // let spliced;
36+ // let isComplete = true;
37+ // console.log('a', a, 'b', b);
38+ // console.log('arr', arr);
39+ // // Remove zero from the right
40+ // while(isComplete) {
41+ // if (arr[b] === '1') {
42+ // spliced = arr;
43+ // isComplete = false;
44+ // break;
45+ // }
4146
42- if ( arr [ a ] !== arr [ b ] ) {
43- // Splice array
44- spliced = arr . splice ( 0 , b ) ;
45- isComplete = false ;
46- break ;
47- }
48- a -- ;
49- b -- ;
50- }
51-
52- N = spliced . join ( '' ) ;
47+ // if (arr[a] !== arr[b]) {
48+ // // Splice array
49+ // spliced = arr.splice(0, b);
50+ // isComplete = false;
51+ // break;
52+ // }
53+ // a--;
54+ // b--;
55+ // }
56+ // console.log('Spliced', spliced);
57+ // N = spliced.join('');
5358
59+ // let i = 0;
60+ // let counter = 0;
61+ // for (let j = 1; j < N.length; j++) {
62+ // if (N[i] !== N[j]) {
63+ // if ((j - i) > counter) {
64+ // counter = j - i;
65+ // }
66+ // i = j;
67+ // }
68+ // }
69+ // return counter;
70+
71+
72+ /*
73+ * This is optimal compared to the one above.
74+ */
75+ let bi = ( N >>> 0 ) . toString ( 2 ) ;
76+ let maxGap = 0 ;
5477 let i = 0 ;
55- let counter = 0 ;
56- for ( let j = 1 ; j < N . length ; j ++ ) {
57- if ( N [ i ] !== N [ j ] ) {
58- if ( ( j - i ) > counter ) {
59- counter = j - i ;
60- }
61- i = j ;
62- }
78+ let j = 1 ;
79+ console . log ( 'Binary' , bi ) ;
80+ // Use sliding window.
81+ // Keep an index of i and j.
82+ // Loop through the string,
83+ while ( j <= bi . length ) {
84+ if ( bi [ j ] == 1 && 1 == bi [ i ] ) {
85+ console . log ( i , j ) ;
86+ let tempMax = ( j - i ) - 1 ;
87+ maxGap = Math . max ( tempMax , maxGap ) ;
88+ console . log ( 'Temp' , maxGap ) ;
89+ i = j ;
90+ j ++ ;
91+ } else if ( bi [ i ] == 1 && bi [ j ] == 0 ) {
92+ j ++ ;
93+ } else {
94+ i ++ ;
95+ j ++ ;
96+ }
6397 }
64- return counter ;
98+ // when you encounter a zero, start counting until you reach a one
99+ // reset the maxGap to the current if current is greater
100+ // return maxGap
101+ return maxGap ;
65102} ;
66103
67104module . exports = binaryGap ;
0 commit comments