This should work:
public static int CountZerosBetweenOnes(string binary)
{
var indicesOfOnes =
binary.Select((c, i) => new {c, i})
.Where(x => x.c == '1')
.Select(x => x.i);
return
indicesOfOnes
.Zip(indicesOfOnes.Skip(1), (a, b) => b - a - 1)
.DefaultIfEmpty(0)
.Max();
}
It does assume that binary
does not contain any characters other than 1
and 0
.
If you want a version that accepts an int
:
public static int CountZerosBetweenOnes(int binary)
{
var indicesOfOnes =
Convert.ToString(binary, 2)
.Select((c, i) => new {c, i})
.Where(x => x.c == '1')
.Select(x => x.i);
return
indicesOfOnes
.Zip(indicesOfOnes.Skip(1), (a, b) => b - a - 1)
.DefaultIfEmpty(0)
.Max();
}
I tested this with the following test code, which outputs the expected result:
public static void Main(string[] args)
{
test("0000000000000"); // Outputs 0
test("0000100010000"); // Outputs 3
test("1111111111111"); // Outputs 0
test("1000000000001"); // Outputs 11
test("1000000000000"); // Outputs 0
test("0000000000001"); // Outputs 0
test("1010101010101"); // Outputs 1
test("1001000100001"); // Outputs 4
}
static void test(string s)
{
Console.WriteLine(CountZerosBetweenOnes(s));
}
Or run it on .Net Fiddle here: https://dotnetfiddle.net/H2Mt8w