Minimum absolute difference between N and any power of 2 | Function to return the highest power of 2 less than or equal to n ; Function to return the smallest power of 2 greater than or equal to n ; Function that returns the minimum absolute difference between n and any power of 2 ; Driver code
function prevPowerof2 ( n ) { var p = parseInt ( Math . log ( n ) / Math . log ( 2 ) ) ; return parseInt ( Math . pow ( 2 , p ) ) ; } function nextPowerOf2 ( n ) { var p = 1 ; if ( n && ! ( n & ( n - 1 ) ) ) return n ; while ( p < n ) p <<= 1 ; return p ; } function minDiff ( n ) { var low = prevPowerof2 ( n ) ; var high = nextPowerOf2 ( n ) ; return Math . min ( n - low , high - n ) ; } var n = 6 ; document . write ( minDiff ( n ) ) ;