Bitwise AND of sub | Python implementation of the approach ; Function to return the minimum possible value of | K - X | where X is the bitwise AND of the elements of some sub - array ; Check all possible sub - arrays ; Find the overall minimum ; No need to perform more AND operations as | k - X | will increase ; Driver code
import sys NEW_LINE def closetAND ( arr , n , k ) : NEW_LINE INDENT ans = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT X = arr [ i ] ; NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT X &= arr [ j ] ; NEW_LINE ans = min ( ans , abs ( k - X ) ) ; NEW_LINE if ( X <= k ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT arr = [ 4 , 7 , 10 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( closetAND ( arr , n , k ) ) ; NEW_LINE