@@ -11,7 +11,7 @@ Example 1:
11
11
Input: 22
12
12
Output: 2
13
13
Explanation:
14
- 22 in binary is 0b10110 .
14
+ 22 in binary is 10110 .
15
15
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
16
16
The first consecutive pair of 1's have distance 2.
17
17
The second consecutive pair of 1's have distance 1.
@@ -21,42 +21,55 @@ Example 2:
21
21
Input: 5
22
22
Output: 2
23
23
Explanation:
24
- 5 in binary is 0b101 .
24
+ 5 in binary is 0101 .
25
25
Example 3:
26
26
27
27
Input: 6
28
28
Output: 1
29
29
Explanation:
30
- 6 in binary is 0b110 .
30
+ 6 in binary is 0110 .
31
31
Example 4:
32
32
33
33
Input: 8
34
34
Output: 0
35
35
Explanation:
36
- 8 in binary is 0b1000 .
36
+ 8 in binary is 01000 .
37
37
There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.
38
38
*/
39
39
40
40
/**
41
41
* @param {number } N
42
42
* @return {number }
43
43
*/
44
- var binaryGap = function ( N ) {
45
- var maxDist = 0 ;
46
- var currentDist = 0 ;
47
- while ( N > 0 ) {
48
- const bit = N % 2 ;
49
- N >>= 1 ;
50
- if ( bit === 1 ) {
51
- currentDist = 1 ;
52
- while ( N > 0 && N % 2 === 0 ) {
53
- currentDist ++ ;
54
- N >>= 1 ;
55
- }
56
- if ( N !== 0 && currentDist > maxDist ) maxDist = currentDist ;
44
+
45
+ const binaryGap = ( n ) => {
46
+ let decimalNumber = n ;
47
+ let binaryNumber = "" ;
48
+ while ( decimalNumber !== 0 ) {
49
+ let result = decimalNumber % 2 ;
50
+ if ( result === 0 ) {
51
+ decimalNumber = decimalNumber / 2 ;
52
+ binaryNumber = result . toString ( ) + binaryNumber ;
53
+ }
54
+ if ( result === 1 ) {
55
+ decimalNumber = ( decimalNumber - 1 ) / 2 ;
56
+ binaryNumber = result . toString ( ) + binaryNumber ;
57
+ }
58
+ }
59
+ let positionsWithOne = [ ] ;
60
+ for ( let i = 0 ; i < binaryNumber . length ; i ++ ) {
61
+ if ( binaryNumber [ i ] === "1" ) {
62
+ positionsWithOne . push ( i ) ;
57
63
}
58
64
}
59
- return maxDist ;
60
- } ;
61
65
66
+ let distance = 0 ;
67
+ for ( let j = 0 ; j < positionsWithOne . length - 1 ; j ++ ) {
68
+ distance =
69
+ distance <= positionsWithOne [ j + 1 ] - positionsWithOne [ j ]
70
+ ? positionsWithOne [ j + 1 ] - positionsWithOne [ j ]
71
+ : distance ;
72
+ }
73
+ return distance ;
74
+ } ;
62
75
module . exports . binaryGap = binaryGap ;
0 commit comments