text: Highest power of 2 less than or equal to given Integer | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; int powOfPositive ( int n ) { int pos = floor ( log2 ( n ) ) ; return pow ( 2 , pos ) ; } int powOfNegative ( int n ) { int pos = ceil ( log2 ( n ) ) ; return ( -1 * pow ( 2 , pos ) ) ; } void highestPowerOf2 ( int n ) { if ( n > 0 ) { cout << powOfPositive ( n ) ; } else { n = - n ; cout << powOfNegative ( n ) ; } } int main ( ) { int n = -24 ; highestPowerOf2 ( n ) ; return 0 ; }