Highest power of 2 less than or equal to given Integer | Java 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
class GFG { static int powOfPositive ( int n ) { int pos = ( int ) Math . floor ( ( Math . log ( n ) / Math . log ( 2 ) ) ) ; return ( int ) Math . pow ( 2 , pos ) ; } static int powOfNegative ( int n ) { int pos = ( int ) Math . ceil ( ( Math . log ( n ) / Math . log ( 2 ) ) ) ; return ( int ) ( - 1 * Math . pow ( 2 , pos ) ) ; } static void highestPowerOf2 ( int n ) { if ( n > 0 ) { System . out . println ( powOfPositive ( n ) ) ; } else { n = - n ; System . out . println ( powOfNegative ( n ) ) ; } } public static void main ( String [ ] args ) { int n = - 24 ; highestPowerOf2 ( n ) ; } }