Reputation: 13
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;
}
Upvotes: 0
Views: 1465
Reputation: 457
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.
Upvotes: 2
Reputation: 682
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;
}
}
Upvotes: 0