Minimum absolute difference between N and any power of 2 | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int prevPowerof2 ( int n ) { int p = ( int ) log2 ( n ) ; return ( int ) pow ( 2 , p ) ; } int nextPowerOf2 ( int n ) { int p = 1 ; if ( n && ! ( n & ( n - 1 ) ) ) return n ; while ( p < n ) p <<= 1 ; return p ; } int minDiff ( int n ) { int low = prevPowerof2 ( n ) ; int high = nextPowerOf2 ( n ) ; return min ( n - low , high - n ) ; } int main ( ) { int n = 6 ; cout << minDiff ( n ) ; return 0 ; }