Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save P-A-R-U-S/a6d69251c3c3b2d604a6692307c8dee9 to your computer and use it in GitHub Desktop.
Save P-A-R-U-S/a6d69251c3c3b2d604a6692307c8dee9 to your computer and use it in GitHub Desktop.
Flip Bit to Win: Flip one bit to get longest sequence of 1s
package Part_5
import (
"testing"
)
/*
Flip Bit to Win: You have an integer and you can flip exactly one bit from a 13 to a 1.Write code to find the length of
the longest sequence of ls you could create.
EXAMPLE
Input: 1775 (or : 1110111101111) Output: 8
Hints: #159, #226, #314, #352
*/
/*
Имеется целое число, в котором можно изменить ровно один бит из О в 1.
Напишите код для определения длины самой длинной последовательности единиц, которая может быть при этом получена.
Пример:
Ввод: 1775 (или: 11011101111}
Вывод: 8
Подсказки: 159,226,314,352
*/
func flipBitToWin(v uint64) int {
l := 64
var zeroCounter, maxCounter, pCounter, cCounter, max int
for i:=l-1;i>=0;i--{
if (v & (0x0000_0000_0000_0001 << i)) > 0 {
zeroCounter = 0
cCounter++
maxCounter = pCounter + cCounter
} else {
zeroCounter++
if zeroCounter == 1 {
cCounter++
maxCounter = cCounter
pCounter = cCounter
cCounter = 0
} else {
pCounter = 0
}
}
if max < maxCounter {
max = maxCounter
}
}
return max
}
func Test_Flip_Bit_to_Win(t *testing.T) {
testDatas := []struct{
v uint64
result int
}{
// 110 1110 1111
{1775, 8 },
{0, 1 },
{552, 3},
{555, 4},
// 1111111111111111011111111111111
{2147467263, 31},
// 00011011 01101101 10110110 11011011
{460175067, 5},
}
for _, td := range testDatas {
r := flipBitToWin(td.v)
if r != td.result {
t.Errorf("Source:%d\nExpected: %d, \nActual: %d",
td.v,
td.result,
r)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment