text: Highest power of 2 less than or equal to given Integer | Python3 implementation of the above approach ; Function to return the lowest power of 2 close to given positive number ; Floor function is used to determine the value close to the number ; Function to return the lowest power of 2 close to given negative number ; Ceil function is used for negative numbers as - 1 > - 4. It would be opposite to positive numbers where 1 < 4 ; Function to find the highest power of 2 ; To check if the given number is positive or negative ; If the number is negative , then the ceil of the positive number is calculated and negative sign is added ; Driver code
code: from math import floor , ceil , log2 NEW_LINE def powOfPositive ( n ) : NEW_LINE INDENT pos = floor ( log2 ( n ) ) ; NEW_LINE return 2 ** pos ; NEW_LINE DEDENT def powOfNegative ( n ) : NEW_LINE INDENT pos = ceil ( log2 ( n ) ) ; NEW_LINE return ( - 1 * pow ( 2 , pos ) ) ; NEW_LINE DEDENT def highestPowerOf2 ( n ) : NEW_LINE INDENT if ( n > 0 ) : NEW_LINE INDENT print ( powOfPositive ( n ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT n = - n ; NEW_LINE print ( powOfNegative ( n ) ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = - 24 ; NEW_LINE highestPowerOf2 ( n ) ; NEW_LINE DEDENT