Find the nearest power of 2 for every array element | C ++ program to implement the above approach ; Function to find nearest power of two for every element in the given array ; Traverse the array ; Calculate log of the current array element ; Find the nearest ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestPowerOfTwo ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int lg = log2 ( arr [ i ] ) ; int a = pow ( 2 , lg ) ; int b = pow ( 2 , lg + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) cout << a << " ▁ " ; else cout << b << " ▁ " ; } } int main ( ) { int arr [ ] = { 5 , 2 , 7 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nearestPowerOfTwo ( arr , N ) ; return 0 ; }