Skip to content

Instantly share code, notes, and snippets.

@kkt-ee
Created January 4, 2020 17:02
Show Gist options
  • Save kkt-ee/ce8fc82f66c027c8821afab2ba6920c9 to your computer and use it in GitHub Desktop.
Save kkt-ee/ce8fc82f66c027c8821afab2ba6920c9 to your computer and use it in GitHub Desktop.
"""
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
"""
def countBits(n):
b = bin(n)[2:]
return sum([int(x) for x in b])
#OR
def countBits(n):
return bin(n).count("1")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment