Minimum absolute difference between N and a power of 2 | Function to return the minimum difference between N and a power of 2 ; Power of 2 closest to n on its left ; Power of 2 closest to n on its right ; Return the minimum abs difference ; Driver code
function minAbsDiff ( n ) { let left = 1 << ( Math . floor ( Math . log ( n ) / Math . log ( 2 ) ) ) ; let right = left * 2 ; return Math . min ( ( n - left ) , ( right - n ) ) ; } let n = 15 ; document . write ( minAbsDiff ( n ) ) ;