Re: Count maximum contiguous set bits in an integer .



Vish wrote:
> I have written a program to count the maximum contiguous set bits in
> an integer.
> Like if my binary representation of integer is :
> 1100111 : then output should be 3.
> 111000111110000101010111111 : then output should be 6.
>
> I am including the snippet below.
> How can I optimize this code and also is there a one liner to
> implement the same.
> (Like for power of 2 we have got (number & (number -1))).

How about a 5 liner?

int longest1BitsCount (unsigned long l) {
int i;
for (i=0; l; i++) l &= l + l;
return i;
}

Like any other program, I have no idea what this does on a 1s
complement machine (and don't really care).

---
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

.



Relevant Pages