Find the nearest power of 2 for every array element | Java program to implement the above approach ; Function to find the nearest power of two for every element of the given array ; Traverse the array ; Calculate log of the current array element ; Find the nearest ; Driver Code
import java . io . * ; class GFG { static void nearestPowerOfTwo ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int lg = ( int ) ( Math . log ( arr [ i ] ) / Math . log ( 2 ) ) ; int a = ( int ) ( Math . pow ( 2 , lg ) ) ; int b = ( int ) ( Math . pow ( 2 , lg + 1 ) ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) System . out . print ( a + " ▁ " ) ; else System . out . print ( b + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 2 , 7 , 12 } ; int N = arr . length ; nearestPowerOfTwo ( arr , N ) ; } }