diff --git a/bit_manipulation/README.md b/bit_manipulation/README.md index 3f5e028beb8e..cb332f42ac8d 100644 --- a/bit_manipulation/README.md +++ b/bit_manipulation/README.md @@ -9,3 +9,22 @@ Bit manipulation is the act of manipulating bits to detect errors (hamming code) * * * + +## Example + +Below is a simple example using the `get_set_bits_count_using_brian_kernighans_algorithm` +function from [bit_manipulation/count_number_of_one_bits.py](bit_manipulation/count_number_of_one_bits.py). + +```python +from bit_manipulation.count_number_of_one_bits import get_set_bits_count_using_brian_kernighans_algorithm + +print(get_set_bits_count_using_brian_kernighans_algorithm(25)) # 3 +print(get_set_bits_count_using_brian_kernighans_algorithm(58)) # 4 +``` + +This repository also includes doctest examples in the implementation that can be run with: + +```bash +python3 bit_manipulation/count_number_of_one_bits.py +``` + diff --git a/tests/test_count_number_of_one_bits.py b/tests/test_count_number_of_one_bits.py new file mode 100644 index 000000000000..d164e0e75157 --- /dev/null +++ b/tests/test_count_number_of_one_bits.py @@ -0,0 +1,22 @@ +import unittest + +from bit_manipulation.count_number_of_one_bits import ( + get_set_bits_count_using_brian_kernighans_algorithm, + get_set_bits_count_using_modulo_operator, +) + + +class TestCountSetBits(unittest.TestCase): + def test_examples(self): + self.assertEqual(get_set_bits_count_using_brian_kernighans_algorithm(25), 3) + self.assertEqual(get_set_bits_count_using_brian_kernighans_algorithm(58), 4) + self.assertEqual(get_set_bits_count_using_modulo_operator(37), 3) + self.assertEqual(get_set_bits_count_using_modulo_operator(0), 0) + + def test_negative_input_raises(self): + with self.assertRaises(ValueError): + get_set_bits_count_using_brian_kernighans_algorithm(-1) + + +if __name__ == "__main__": + unittest.main()