C: Longest Sequence Of Ones
Monday, 26 July 2010 07:34

Below is the answer to "Find the longest sequence of bits set to one in an array?". Apparently some form of this question has been used by Microsoft during interviews.

The solution below is pretty basic, and can be improved in a few ways. For example:

  • the 'inner loop' doing the bit shift may be avoided by comparing the current byte to 0x00 or 0xff

#include <stdio.h>
#include <stdlib.h>

typedef struct LBS {
	int bitcount;
	int startbyte;
	int startbit;
} LBS;

LBS findLongest(unsigned char * testbytes, int numbytes);

int main(void) {

	unsigned char testbytes[5 * 8] = { 0xff, 0xff, 0xff, 0xff, 0x00, 0x00,
			0xff, 0xff, 0xff, 0xff, 0x00, 0x07, 0xff, 0xff, 0xff, 0xff, 0xf0,
			0x00, 0x00, 0x00 };

	LBS result = findLongest(testbytes, sizeof(testbytes));

	printf("Result: Length: %d bits, Start Byte %d, Start Bit %d\n",
			result.bitcount, result.startbyte, result.startbit);

	return 0;
}

LBS findLongest(unsigned char * testbytes, int numbytes) {
	int i = 0;
	int j = 0;
	LBS result = { 0, 0, 0 };
	LBS current = { 0, 0, 0 };

	for (i = 0; i < numbytes; i += 1) {
		for (j = 0; j < 8; j += 1) {

			if (((testbytes[i] << j) & 0x80) == 0x80) {
				if (current.bitcount == 0) {
					current.bitcount = 1;
					current.startbyte = i;
					current.startbit = j;
				} else {
					current.bitcount += 1;
				}
			} else {
				if (current.bitcount > result.bitcount) {
					result = current;
				}
				current.bitcount = 0;
				current.startbyte = 0;
				current.startbit = 0;
			}

		}
	}
	if (current.bitcount > result.bitcount) {
		result = current;
	}
	return result;
}