Snippet: bitcount()

Eugene Leitl eugene.leitl at lrz.uni-muenchen.de
Fri Jul 16 20:00:34 EDT 1999


Ouch, ouch. That was really _inefficient_. At least you could nybble
or byte-wise lookup, and there should be lots of bigmask magic which
does in in O(logN). Consider bitcounting L's. 

Klaus Alexander Seistrup writes:
 >   G'day mates.
 > 
 > Here's a snippet for the repository:
 > 
 > # The function bitcount() will count the number
 > # of bits in a number, iterating at most as many
 > # times as the number of bits.
 > #
 > def bitcount(x):
 >     n = 0
 >     while x:
 >         x = x & (x-1)
 >         n = n + 1
 >     # end while
 >     return n
 > # end def bitcount
 > 
 > 
 > Cheers,
 > 
 >   //Klaus
 > 
 > -- 
 > ···[ Magnetic Ink ]·················································· ><> ···
 > ···[ http://www.magnetic-ink.dk/ ]···········································
 > 
 > -- 
 > http://www.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list