# Bitwise AND of sub-array closest to K in C++

In this problem, we are given an array arr[] of size n and an integer k. Our task is to find the subarray within from index i to j and compute bitwise AND of all its elements. After this print minimum value of abs(K- (bitwise AND of subarray)).

Let’s take an example to understand the problem,

Input − arr[] = {5, 1}, k = 2

Output

To solve the problem, there can be a few methods.

One simple solution will be using the direct method. By finding bitwise AND for all sub-arrays then finding the |K-X|.

Step 1 − Find the bitwise AND for all sub-arrays.

Step 2 − For each value found from above step 1 (say X). Find the value of |k - X|.

Step 3 − Store the minimum value found above in a min variable.

Step 4 − At the end, print min.

## Example

Program to illustrate the working of our solution,

Live Demo

#include <iostream>
using namespace std;
int CalcBitwiseANDClosestK(int arr[], int n, int k){
int minimum = 1000;
for (int i = 0; i < n; i++) {
int X = arr[i];
for (int j = i; j < n; j++) {
X &= arr[j];
minimum = min(minimum, abs(k - X));
}
}
return minimum;
}
int main() {
int arr[] = { 1, 6 , 4, 9, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 5;
cout<<"Minimum value difference between Bitwise AND of sub-array and K is "<<CalcBitwiseANDClosestK(arr, n, k);
return 0;
}

## Output

Minimum value difference between Bitwise AND of sub-array and K is 1

Another solution could be using observing the AND operation in the sub-array. The bitwise AND has a trait that it will never increase. So, we have to keep a check on the minimum difference which will increase when X ≤ K.

## Example

Live Demo

#include <iostream>
using namespace std;
int CalcBitwiseANDClosestK(int arr[], int n, int k){
int minimum = 1000000;
for (int i = 0; i < n; i++) {
int BitwiseAND = arr[i];
for (int j = i; j < n; j++) {
BitwiseAND &= arr[j];
minimum = min(minimum, abs(k - BitwiseAND));
if (BitwiseAND <= k)
break;
}
}
return minimum;
}
int main() {
int arr[] = {1, 6 , 4, 9, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 5;
cout<<"Minimum value difference between Bitwise AND of sub-array and K is "<<CalcBitwiseANDClosestK(arr, n, k);
return 0;
}

## Output

Minimum value difference between Bitwise AND of sub-array and K is 1