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; } 
3
  • Possible duplicate of Foreach loop, determine which is the last iteration of the loop Commented Aug 27, 2018 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); Commented Aug 27, 2018 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. Commented Aug 27, 2018 at 15:26

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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; } } 

2 Comments

Thank you sir @Greg the other answer is gone. I can't upvote your answer I wonder why.
No problem. May have to wait a certain period of time before you can.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.