C How can I count length of the longest continuous sequence of 0s in long variable?

Viewed 311

I have a simple function which counts me how many 0s are in long variable where is a binary representation of some positive integer value. But I need to implement a new feature which will return the length of the longest continuous sequence of 0s...

Function for count of 0s:

int nullSeq(long binn)
{
    int count=0;

    if(binn==0)
        return 1;

    while(binn!=0)
    {
        if ((binn & 1) == 0)
        {
            count++;
        }
        binn=binn >> 1;
    }

    return count;
}

F.e. the number 559. The binary representations of 559 is 1000101111. The 0 count function will return 4. The longest continuous sequence of zeros should be 3. Until now I unconsciously used the value of all zeros as a longest sequence. It worked for some numbers. But I need to implement a new function which will find the longest zero sequence.

1 Answers

You're actually counting the total number of zeros you find. You need to increase the counter when you find a 0 and set the counter to 0 when you find a 1, and you have to keep track of the largest value of the counter.

int nullSeq(long binn)
{
    int count=0, maxcount=0;

    if(binn==0) {
        return 1;
    }

    while(binn!=0) {
        if ((binn & 1) == 0) {
            count++;
            if (count > maxcount) {
                maxcount = count;
            }
        } else {
            count = 0;
        }
        binn=binn >> 1;
    }
    return maxcount;
}
Related