Created
June 8, 2022 09:03
-
-
Save horvatha/b0ea6a5f832d685cb661532e3b109d9b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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