Minimum absolute difference between N and a power of 2 | Java implementation of the above approach ; 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
class GFG { static int minAbsDiff ( int n ) { int left = 1 << ( ( int ) Math . floor ( Math . log ( n ) / Math . log ( 2 ) ) ) ; int right = left * 2 ; return Math . min ( ( n - left ) , ( right - n ) ) ; } public static void main ( String [ ] args ) { int n = 15 ; System . out . println ( minAbsDiff ( n ) ) ; } }