From b31bfaa96f28042a168724d1554a2b158c62dea7 Mon Sep 17 00:00:00 2001 From: Sharnabh Banerjee Date: Wed, 4 Oct 2023 17:46:17 +0530 Subject: [PATCH] Fixes #9347 Fixes #9347 --- ..._2_less_than_or_equal_to_a_given_number.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 bit_manipulation/Add_largest_power_of_2_less_than_or_equal_to_a_given_number.py diff --git a/bit_manipulation/Add_largest_power_of_2_less_than_or_equal_to_a_given_number.py b/bit_manipulation/Add_largest_power_of_2_less_than_or_equal_to_a_given_number.py new file mode 100644 index 000000000000..eb3648322f21 --- /dev/null +++ b/bit_manipulation/Add_largest_power_of_2_less_than_or_equal_to_a_given_number.py @@ -0,0 +1,43 @@ +""" +Fixes #9347 +Name : Sharnabh Banerjee + +""" + + +def add_largest(num: int) -> int: + """ + Add Largest Power of 2 less then or equal to a given number + >>> add_largest(5.3) + Traceback (most recent call last): + ... + TypeError: num must be an integer !! + >>> add_largest(5) + 9 + >>> add_largest(10) + 18 + >>> add_largest(99) + 163 + >>> add_largest(-10) + 0 + >>> add_largest(999) + 1511 + + """ + if isinstance(num, float): + raise TypeError("num must be an integer !!") + if num <= 0: + return 0 + temp = num + count = 0 + while num != 1: + num = num >> 1 + count += 1 + res = 2**count + temp + return res + + +if __name__ == "__main__": + import doctest + + doctest.testmod()