# Bitwise AND Hackerrank problem solution

##### Bitwise AND Hackerrank

Given set S={1,2,3,….N}. Find two integers, A and B (where AInput Format

The first line contains an integer, T, the number of test cases.
Each of the T subsequent lines defines a test case as 2 space-separated integers, N and K, respectively.

Constraints

1<=T<=103
2<=N<=103
2<=K<=N Output Format

For each test case, print the maximum possible value of A&B on a new line.

Sample Input

```3 5 2 8 5 2 2```
Sample Output

```1 4 0```
Explanation

N=5, K=2, S={1,2,3,4,5}

All possible values of A and B are:

The maximum possible value of A&B that is also <(K=2) is 1, so we print 1 on a new line.

##### solution
```#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;
void maxAnd(int n, int k)
{
int temp = 1;
vector<int> andValues;

while (temp < n) {

for (int i = 0; i < n+1; ++i) {
if (temp < i) {

if ((temp&i) < k) {
andValues.push_back((temp&i));

}
}
}

temp++;
}

double max = *max_element(andValues.begin(), andValues.end());
cout << max << endl;
}

int main(){
int t;
cin >> t;
for(int a0 = 0; a0 < t; a0++){
int n;
int k;
cin >> n >> k;
maxAnd(n,k);
}

return 0;
}
```
``````import java.util.*;

public class Solution {
public static int findMaximum(int n, int k){
int max = 0;
int a = n - 1; // we are constrained by a < b
while(a-- > 0) {
for(int b = a + 1; b <= n; b++){
int test = a & b;
if( 	test < k
&& 	test > max ){
max = test;
}
}
}
return max;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i = 0; i < t; i++){
int n = in.nextInt();
int k = in.nextInt();
System.out.println( findMaximum(n, k) );
}
in.close();
}
}``````
``````for _ in xrange(int(raw_input())):
n, k = map(int, raw_input().split())
a = k - 1
b = ~a & -~a
if a | b > n:
print a - 1
else:
print a``````

### hasectic

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi