Find the nearest power of 2 for every array element | 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
function nearestPowerOfTwo ( arr , N ) { for ( i = 0 ; i < N ; i ++ ) { var lg = parseInt ( ( Math . log ( arr [ i ] ) / Math . log ( 2 ) ) ) ; var a = parseInt ( ( Math . pow ( 2 , lg ) ) ) ; var b = parseInt ( ( Math . pow ( 2 , lg + 1 ) ) ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) document . write ( a + " " ) ; else document . write ( b + " " ) ; } } var arr = [ 5 , 2 , 7 , 12 ] ; var N = arr . length ; nearestPowerOfTwo ( arr , N ) ;