0

I am trying to build a function that counts the number of zero between ones. My function is doing just fine for binaries that starts and end with one. But the problem is if the given binary is 100000, it is returning 5. But it should return zero because it is not between ones.

Here is the code.

private static int solution1(int N)
{
    string binary = Convert.ToString(N, 2);
    int gap = 0;
    int longestgap = 0;

    foreach (char Z in binary)
    {
        if (Z == '0') gap++;
        if (gap > longestgap) longestgap = gap;
        if (Z == '1') gap = 0;
    }
    return longestgap;
}
AustinWBryan
  • 2,968
  • 3
  • 17
  • 35
Future
  • 13
  • 5
  • Possible duplicate of [Foreach loop, determine which is the last iteration of the loop](https://stackoverflow.com/questions/7476174/foreach-loop-determine-which-is-the-last-iteration-of-the-loop) – Dmitry Pavliv Aug 27 '18 at 15:20
  • 1
    Just for fun, you could strip any leading and trailing `0` characters and then split the string by `1` and count the longest substring: `int longestGap = Convert.ToString(N, 2).Trim('0').Split('1').Max(x => x.Length);` – Matthew Watson Aug 27 '18 at 15:25
  • I really hate to bring in regex ... but how about regexing for matches of the desired pattern and then max in on the results? - Forget it. @MatthewWatson 's method is even better. – Fildor Aug 27 '18 at 15:26

2 Answers2

2

All you need to do is move the second if. You dont want to override the longest gap everytime, only if you know it is definitely between two 1's.

if (Z == '0')
{
    gap++;
}
else // if (Z == '1')
{
    if (gap > longestgap)
    {
        longestgap = gap;
    }

    gap = 0;
}

This way, even if the gap keeps counting up until the end of your binary, if you don't find a second '1', the longest gap will still be 0.

AustinWBryan
  • 2,968
  • 3
  • 17
  • 35
Alexander Moser
  • 397
  • 3
  • 16
  • 1
    You're welcome. This btw doesn't cover the case of having a binary like 0001001, since it starts counting immediately, instead of at the first `'1'`. But I think `Convert.ToString(N, 2)` will always return a binary with a leading 1 unless you enter 0. – Alexander Moser Aug 27 '18 at 15:32
0

Not really tested, but something like this should work:

bool firstOneFound = false; // To account for the case "00001"
foreach (char Z in binary)
{
    if (Z == '0')
    {
        if(firstOneFound)
            gap++;
    }
    else if (Z == '1')
    {
        if (gap > longestgap)
            longestgap = gap;

        firstOneFound = true;
        gap = 0;
    }
}

If you don't need to use a foreach loop, this seems cleaner:

 for(int i = binary.IndexOf("1"); i < binary.Length; i++)
 {
     char Z = binary[i];
     if (Z == '0')
     {
         gap++;
     }
     else if (Z == '1')
     {
         if (gap > longestgap)
             longestgap = gap;

         gap = 0;
      }
  }
eye_am_groot
  • 692
  • 6
  • 18