Minimum absolute difference between N and a power of 2 | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minAbsDiff ( int n ) { int left = 1 << ( ( int ) floor ( log2 ( n ) ) ) ; int right = left * 2 ; return min ( ( n - left ) , ( right - n ) ) ; } int main ( ) { int n = 15 ; cout << minAbsDiff ( n ) ; return 0 ; }