-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathfind-the-longest-gap.js
83 lines (69 loc) · 2.08 KB
/
find-the-longest-gap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
function gap(num) {
// convert the number to a binary string
const binaryString = num.toString(2);
// a place to store the length of the longest segment
// initialized to zero
let longestSegment = 0;
// a place to store the length of the current longest segment
// initialized to zero
let currentLongestSegment = 0;
// iterate over the binary string
for (let i = 0; i < binaryString.length; i++) {
const bit = binaryString[i];
// if the current value is 1
if (bit == 1) {
// check if current longest segment is greater than overall longest segment
if (currentLongestSegment > longestSegment) {
// if so, update overall longest segment
longestSegment = currentLongestSegment;
}
// reset current longest segment to 0
currentLongestSegment = 0;
} else {
// if the current value is a 0
// increment the current longest segment
currentLongestSegment += 1;
}
}
// return the longest segment
return longestSegment;
}
// Math.max(..."100010".toString(2).match(/([0]+)/g).map(n=>n.length))
// (s) => Math.max (...(s.replace(/1/g, ' ').split(' ').map (s => s.length)))
function gap(num) {
const binaryString = num.toString(2);
let longestSegment = 0;
let currentLongestSegment = 0;
for (let i = 0; i < binaryString.length; i++) {
const bit = binaryString[i];
if (bit == 1) {
if (currentLongestSegment > longestSegment) {
longestSegment = currentLongestSegment;
}
currentLongestSegment = 0;
} else {
currentLongestSegment += 1;
}
}
return longestSegment;
}
function gap(num) {
let longestSegment = 0;
let currentLongestSegment = 0;
for (let i = 0; i < 32; i++) {
const bit = (num>>>i)&1;
if (bit == 1) {
if (currentLongestSegment > longestSegment) {
longestSegment = currentLongestSegment;
}
currentLongestSegment = 0;
} else {
currentLongestSegment += 1;
}
}
return longestSegment;
}
console.log(gap(9),2);
console.log(gap(529),4);
console.log(gap(20),1);
console.log(gap(15),0);