I am aware this problem has been asked before but in java e.g Printing longest sequence of zeroes. This is a similar problem but in C#. A brief explanation of the problem is to find the longest sequence of zeroes in a binary representation of an Integer. For instance, the Integer 529 in binary gives 1000010001 and the longest sequence of zeroes is 4. So far I have achieved this using the following code
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static int Solution(int N)
{
List<int> occurenceCount = new List<int>();
int Counter=0,value;
if(N == 0)
{
Console.WriteLine(0);
return 0;
}
else{
string binaryRep = Convert.ToString(N,2);
// find the first occurence of 1
int FirstIndex = binaryRep.IndexOf("1");
// find the last occurence of 1
int LastIndex = binaryRep.LastIndexOf("1");
for(int i = FirstIndex; i<LastIndex+1;)
{
value = i;
while(binaryRep[value++] != '1' )
{
Counter = Counter+1;
}
occurenceCount.Add(Counter);
i= value;
Counter=0;
}
return occurenceCount.Max();
}
}
static void Main()
{
Console.WriteLine(Solution(1041));
}
}
Brief description of the code: If the Integer passed is 0, then 0 is returned else the longest sequence. The convert.ToString() gives the binary representation. To improve the performance, I keep track of the index of the first 1 and the last index of 1 and use this in the for loop. In the while loop, once a 0 is encountered in between two 1's then a counter is incremented until a 1 is encountered and later on added to the List. I would appreciate if any one can tell me how to improve on this.
IEnumerable<int>
and returns anIEnumerable<int>
where each int is the "run length" of the numbers? So for example given the sequence 1, 1, 1, 2, 2, 5, 3, 3, 3, 3, 2 the result would be 3, 2, 1, 4, 1 because there are 3 ones, 2 twos, 1 five, 4 threes and 1 two. Once you have written that program, do you see how you can use it to easily solve this problem? \$\endgroup\$(apply max (map count (set (string/split "1000010001" #"1"))))
\$\endgroup\$