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()