Skip to content

Instantly share code, notes, and snippets.

@horvatha
Created June 8, 2022 09:03
Show Gist options
  • Save horvatha/b0ea6a5f832d685cb661532e3b109d9b to your computer and use it in GitHub Desktop.
Save horvatha/b0ea6a5f832d685cb661532e3b109d9b to your computer and use it in GitHub Desktop.
def ones(num: int, number_of_bytes: int = 4) -> int:
num_ones = 0
for i in range(number_of_bytes * 8):
if (2 ** i) & num:
num_ones += 1
return num_ones
def ones(num: int) -> int:
bin_string = f"{num:b}"
return list(bin_string).count("1")
def test_ones():
assert ones(3) == 2
assert ones(1 + 4 + 64) == 3
assert ones(128) == 1
assert ones(127) == 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment