Q:

Return contiguous 0's in a given binary number

I'm just working through some exercises in C#. I would like to return the number of contiguous 0's in given binary number. For example:
int test1 = 101010;  // Return 1
int test2 = 100101;  // Return 2
int test3 = 100001;  // Return 4
int test4 = 111111;  // Return 0

I have come up with the following code which works for tests 1,2 & 4 but not for test 3.
    public static int continuousZeros(int x)
    {

        char[] charArray = x.ToString().ToCharArray();

        int count = 0;
        int total = 0;

        for (int i = 0; i < charArray.Length; i++)
        {
            if (charArray[i] == '0' && charArray[i - 1] == '0')
            {
                count++; 
            }
            else if (charArray[i] == '0' && charArray[i - 1] == '1')
            {
                total = count + 1;
                count = 0;
            }
        }

        return total;
    }

If I try and add another else if: if (charArray[i] == '1' && charArray[i - 1] == '0') I get an IndexOutofRangeException. 
I'm also sure there is a more efficient way to accomplish this?

A:

As others have mentioned, you're trying to access charArray[-1], which throws an exception. This was my first instinct: 
public static int continuousZeros(int x)
{
    int max = 0;
    int current = 0;

    char[] charArray = x.ToString().ToCharArray();

    for (int i = 0; i < charArray.Length; i++)
    {
        if (charArray[i] == '0')
        {
            current++;
        }
        else
        {
            if (current > max) { max = current; }
            current = 0;
        }
    }

    return max;
}

