Created
May 21, 2013 16:36
-
-
Save anonymous/5621241 to your computer and use it in GitHub Desktop.
Given a list of 10k 32-bit integers, calculate the number of set bits in each. Quickly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
data = list() | |
for i in range(10000): | |
data.append(random.randint(0, 2**32)) | |
bits_set = {0: 0} | |
for i in range(256): | |
bits_set[i] = (i & 1) + bits_set[i / 2] | |
def count_ones(x): | |
return ( | |
bits_set[x & 255] + bits_set[(x >> 8) & 255] + | |
bits_set[(x >> 16) & 255] + bits_set[(x >> 24) & 255]) | |
for x in data: | |
print '%s: %s: %s' % (x, bin(x), count_ones(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment