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
using System ; class GFG { static int closetAND ( int [ ] arr , int n , int k ) { int ans = int . MaxValue ; for ( int i = 0 ; i < n ; i ++ ) { int X = arr [ i ] ; for ( int j = i ; j < n ; j ++ ) { X &= arr [ j ] ; ans = Math . Min ( ans , Math . Abs ( k - X ) ) ; } } return ans ; } public static void Main ( ) { int [ ] arr = { 4 , 7 , 10 } ; int n = arr . Length ; int k = 2 ; Console . WriteLine ( closetAND ( arr , n , k ) ) ; } }