Skip to content

Instantly share code, notes, and snippets.

@jmeridth
Created July 23, 2010 16:38
Show Gist options
  • Save jmeridth/487676 to your computer and use it in GitHub Desktop.
Save jmeridth/487676 to your computer and use it in GitHub Desktop.
get the number of one bits in a number (python)
def num_of_one_bits(num):
total = 0
bits = ""
while(num > 0):
bits += str(num&1)
total += num&1
num>>=1
return total,bits
number = input("Please give an integer: ")
total,bits = num_of_one_bits(number)
print "Number of one bits: " + str(total)
print "bit representation: " + bits[::-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment