Bitwise AND of sub | 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
function closetAND ( arr , n , k ) { let ans = Number . MAX_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { let X = arr [ i ] ; for ( let j = i ; j < n ; j ++ ) { X &= arr [ j ] ; ans = Math . min ( ans , Math . abs ( k - X ) ) ; if ( X <= k ) break ; } } return ans ; } let arr = [ 4 , 7 , 10 ] ; let n = arr . length ; let k = 2 ; document . write ( closetAND ( arr , n , k ) ) ;