I'm trying to write a program to solve an ACM problem, and it has to be very fast. A mathematically fast approach to the problem is to use bitwise computations. However, I'm using python and I'm having trouble performing these computations at bit level. The problems are:
I did consider writing a class such as bitSet in C++, but I have a feeling this will not be very fast either. P.S. the binary digits I'm working with can be as large as 1000 bits and I might have to work with a 1000 such binary digits, so efficiency is imperative.
Here's a well-known algorithm for counting the one-bits:
def bitCount(x):
count = 0
while x != 0:
count += 1
x &= (x-1)
return count
The point is that x-1 has the same binary representation as x, except that the least least significant one-bit is cleared to 0 and all the trailing 0's are set to one. So, setting x = x & (x-1)
simply clears the least significant one-bit.