You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* 5.3 Flip Bit to Win: You have an integer and you can flip exactly one bit from a 0 to a 1. Write code to find the length of the longest sequence of 1syou could create.
3
+
4
+
EXAMPLE
5
+
6
+
Input: 1775 (or: 11011101111)
7
+
Output: 8
8
+
9
+
* @param number
10
+
*/
11
+
functionflipBitToWin(number){
12
+
// keep two counters for previous and current ones
13
+
letprevious=0;
14
+
letcurrent=0;
15
+
letmax=0;
16
+
17
+
while(number>0){
18
+
if(number&1){
19
+
current++;
20
+
}else{
21
+
if(previous>0){
22
+
max=Math.max(current+previous+1,max);
23
+
}
24
+
25
+
previous=current;
26
+
current=0;
27
+
}
28
+
29
+
number>>=1;
30
+
}
31
+
32
+
if(previous>0){
33
+
max=Math.max(current+previous+1,max);
34
+
}else{
35
+
max=Math.max(current,max);
36
+
}
37
+
38
+
returnmax;
39
+
}
40
+
41
+
module.exports=flipBitToWin;
42
+
43
+
/*
44
+
45
+
Brute force
46
+
1. number to binary string
47
+
2. iterate to find 0's
48
+
3. change the 0 to 1 and count contiguous 1's
49
+
4. flip back to zero and repeat until last bit
50
+
5. print max contiguous 1's
51
+
52
+
O (x^2), where x is the number of bits
53
+
54
+
Hints: #159, #226, #314, #352
55
+
56
+
# Start with a brute force solution. Can you try all possibilities?
57
+
# Flipping a 0 to a 1 can merge two sequences of 1s-but only if the two sequences are separated by only one O.
58
+
# Each sequence can be lengthened by merging it with an adjacent sequence (if any) or just flipping the immediate neighboring zero.You just need to find the best choice.
59
+
# Try to do it in linear time, a single pass, and 0 (1) space.
0 commit comments