Finding consecutive bit string of 1 or 0

前端 未结 10 692
刺人心
刺人心 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:05

    One simple way would be to simply loop over the bits, and keep track of the number of bits in a row which have had the same value, and the maximum that this value has reached.

    Here's a simple C function which does just this:

    int num_conseq_matching_bits(int n) {
        int i, max, cur, b, prevb;
        prevb = n & 1; /* 0th bit */
        cur = 1;
        max = 1;
        for(i=1; i<32; i++) {
            b = (n >> i) & 1; /* get the i'th bit's value */
            if(b == prevb) {
                cur += 1;
                if(cur > max)
                    max = cur;
            }
            else {
                cur = 1; /* count self */
                prevb = b;
            }
        }
        return max;
    }
    

提交回复
热议问题