Bitwise AND of sub | C ++ 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 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int closetAND ( int arr [ ] , int n , int k ) { int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { int X = arr [ i ] ; for ( int j = i ; j < n ; j ++ ) { X &= arr [ j ] ; ans = min ( ans , abs ( k - X ) ) ; } } return ans ; } int main ( ) { int arr [ ] = { 4 , 7 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << closetAND ( arr , n , k ) ; return 0 ; }