From f22fe4812d8816c96271b1213963e8d8c649c48a Mon Sep 17 00:00:00 2001 From: NA-V10 Date: Fri, 21 Nov 2025 16:24:50 +0530 Subject: [PATCH 1/2] feat: add count_bits algorithm with doctests --- bit_manipulation/count_bits.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 bit_manipulation/count_bits.py diff --git a/bit_manipulation/count_bits.py b/bit_manipulation/count_bits.py new file mode 100644 index 000000000000..e5d36c94eba2 --- /dev/null +++ b/bit_manipulation/count_bits.py @@ -0,0 +1,31 @@ +def count_bits(n: int) -> int: + """ + Count the number of set bits (1s) in the binary representation of a + non-negative integer. + + Examples: + >>> count_bits(0) + 0 + >>> count_bits(1) + 1 + >>> count_bits(5) # 101 + 2 + >>> count_bits(15) # 1111 + 4 + >>> count_bits(16) # 10000 + 1 + """ + if n < 0: + raise ValueError("Input must be non-negative") + + count = 0 + while n > 0: + count += n & 1 + n >>= 1 + + return count + + +if __name__ == "__main__": + import doctest + doctest.testmod() From 7aef9f9a27043c7f9ae2cfc8a928c44bbf1a13e6 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 21 Nov 2025 10:55:49 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- bit_manipulation/count_bits.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bit_manipulation/count_bits.py b/bit_manipulation/count_bits.py index e5d36c94eba2..cebd165b4da1 100644 --- a/bit_manipulation/count_bits.py +++ b/bit_manipulation/count_bits.py @@ -28,4 +28,5 @@ def count_bits(n: int) -> int: if __name__ == "__main__": import doctest + doctest.testmod()