Finding consecutive bit string of 1 or 0

前端 未结 10 699
刺人心
刺人心 2020-11-29 05:27

How to find the length of the longest consecutive bit string(either 1 or 0)?

00000000 11110000 00000000 00000000 -> If it is 0 then length will be 20

11111

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 06:12

    To use the table idea, you need something like

    static struct {
        int lead;  /* leading 0 bits */
        int max;   /* maximum 0 bits */
        int trail; /* trailing 0 bits */
    } table[256] = { ....data.... };
    
    int mostConsecutiveBits(unsigned char *str, int length, bool count_ones) {
        int max = 0; /* max seen so far */
        int trail = 0; /* trailing 0s from previous bytes */
        while (length-- > 0) {
            int byte = *str++;
            if (count_ones)
                byte ^= 0xff;
            if (table[byte].max > max)
                max = table[byte].max;
            if (trail + table[byte].lead > max)
                max = trail + table[byte].lead;
            if (byte)
                trail = table[byte].trail;
            else
                trail += 8;
        }
        return max;
    }
    

    initializing the table is straight-forward, but depends on your bit- and byte-ordering (little endian or big endian).

提交回复
热议问题