File tree 1 file changed +69
-0
lines changed
1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ https://leetcode.com/problems/binary-gap/description/
3
+
4
+ Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.
5
+
6
+ If there aren't two consecutive 1's, return 0.
7
+
8
+ Example 1:
9
+
10
+ Input: 22
11
+ Output: 2
12
+ Explanation:
13
+ 22 in binary is 0b10110.
14
+ In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
15
+ The first consecutive pair of 1's have distance 2.
16
+ The second consecutive pair of 1's have distance 1.
17
+ The answer is the largest of these two distances, which is 2.
18
+ Example 2:
19
+
20
+ Input: 5
21
+ Output: 2
22
+ Explanation:
23
+ 5 in binary is 0b101.
24
+ Example 3:
25
+
26
+ Input: 6
27
+ Output: 1
28
+ Explanation:
29
+ 6 in binary is 0b110.
30
+ Example 4:
31
+
32
+ Input: 8
33
+ Output: 0
34
+ Explanation:
35
+ 8 in binary is 0b1000.
36
+ There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.
37
+ */
38
+
39
+ /**
40
+ * @param {number } N
41
+ * @return {number }
42
+ */
43
+ var binaryGap = function ( N ) {
44
+ var maxDist = 0 ;
45
+ var currentDist = 0 ;
46
+ while ( N > 0 ) {
47
+ const bit = N % 2 ;
48
+ N >>= 1 ;
49
+ if ( bit === 1 ) {
50
+ currentDist = 1 ;
51
+ while ( N > 0 && N % 2 === 0 ) {
52
+ currentDist ++ ;
53
+ N >>= 1 ;
54
+ }
55
+ if ( N !== 0 && currentDist > maxDist ) {
56
+ maxDist = currentDist ;
57
+ }
58
+ }
59
+ }
60
+ return maxDist ;
61
+ } ;
62
+
63
+ var main = function ( ) {
64
+ console . log ( binaryGap ( 22 ) ) ; // 10110
65
+ console . log ( binaryGap ( 8 ) ) ; // 1000
66
+ }
67
+ main ( ) ;
68
+
69
+ module . exports . main = main ;
You can’t perform that action at this time.
0 commit comments