Minimum absolute difference between N and a power of 2 | Python3 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
import math NEW_LINE def minAbsDiff ( n ) : NEW_LINE INDENT left = 1 << ( int ) ( math . floor ( math . log2 ( n ) ) ) NEW_LINE right = left * 2 NEW_LINE return min ( ( n - left ) , ( right - n ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 15 NEW_LINE print ( minAbsDiff ( n ) ) NEW_LINE DEDENT