Highest power of 2 less than or equal to given Integer | 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
function powOfPositive ( n ) { let pos = Math . floor ( Math . log2 ( n ) ) ; return Math . pow ( 2 , pos ) ; } function powOfNegative ( n ) { let pos = Math . ceil ( Math . log2 ( n ) ) ; return ( - 1 * Math . pow ( 2 , pos ) ) ; } function highestPowerOf2 ( n ) { if ( n > 0 ) { document . write ( powOfPositive ( n ) ) ; } else { n = - n ; document . write ( powOfNegative ( n ) ) ; } } let n = - 24 ; highestPowerOf2 ( n ) ;