From 5efaff24d59c27eac617ba887f0fb5e69a618693 Mon Sep 17 00:00:00 2001 From: Tapas Singhal <98687345+Shocker-lov-t@users.noreply.github.com> Date: Thu, 26 Oct 2023 01:32:37 +0530 Subject: [PATCH 1/2] Create find_previous_power_of_two.py --- .../find_previous_power_of_two.py | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 bit_manipulation/find_previous_power_of_two.py diff --git a/bit_manipulation/find_previous_power_of_two.py b/bit_manipulation/find_previous_power_of_two.py new file mode 100644 index 000000000000..486b989b0941 --- /dev/null +++ b/bit_manipulation/find_previous_power_of_two.py @@ -0,0 +1,45 @@ +# https://stackoverflow.com/questions/1322510/given-an-integer-how-do-i-find-the-next-largest-power-of-two-using-bit-twiddlin + +def find_previous_power_of_two(n: int) -> int: + """ + Find the largest power of two that is less than or equal to a given integer. + + >>> find_previous_power_of_two(10) + 8 + >>> find_previous_power_of_two(16) + 16 + >>> find_previous_power_of_two(5) + 4 + >>> find_previous_power_of_two(1) + 1 + >>> find_previous_power_of_two(0) + 0 + >>> find_previous_power_of_two(-5) + Traceback (most recent call last): + ... + ValueError: Input must be a non-negative integer + >>> find_previous_power_of_two(10.5) + Traceback (most recent call last): + ... + TypeError: Input must be an integer + """ + + if not isinstance(n, int): + raise TypeError("Input must be an integer") + + if n < 0: + raise ValueError("Input must be a non-negative integer") + + if n == 0: + return 0 + + power = 1 + while power <= n: + power <<= 1 # Equivalent to multiplying by 2 + + return power >> 1 + +if __name__ == "__main__": + import doctest + + doctest.testmod() From f5878ce8821af8a7e5ebe86deb8db4e5ccd74e2f Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 25 Oct 2023 21:08:38 +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/find_previous_power_of_two.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bit_manipulation/find_previous_power_of_two.py b/bit_manipulation/find_previous_power_of_two.py index 486b989b0941..2cade6d6a96e 100644 --- a/bit_manipulation/find_previous_power_of_two.py +++ b/bit_manipulation/find_previous_power_of_two.py @@ -1,5 +1,6 @@ # https://stackoverflow.com/questions/1322510/given-an-integer-how-do-i-find-the-next-largest-power-of-two-using-bit-twiddlin + def find_previous_power_of_two(n: int) -> int: """ Find the largest power of two that is less than or equal to a given integer. @@ -39,6 +40,7 @@ def find_previous_power_of_two(n: int) -> int: return power >> 1 + if __name__ == "__main__": import doctest