Day 29: Bitwise AND - HackerRank 30 days of code solution
Objective
Welcome to the last day! Today, we're discussing bitwise operations.
Welcome to the last day! Today, we're discussing bitwise operations.
Task
Given set . Find two integers, and (where ), from set such that the value of is the maximum possible and also less than a given integer, . In this case, represents the bitwise AND operator.
Given set . Find two integers, and (where ), from set such that the value of is the maximum possible and also less than a given integer, . In this case, represents the bitwise AND operator.
Input Format
The first line contains an integer, , the number of test cases.
Each of the subsequent lines defines a test case as space-separated integers, and , respectively.
Each of the subsequent lines defines a test case as space-separated integers, and , respectively.
Constraints
Output Format
For each test case, print the maximum possible value of on a new line.
Sample Input
3
5 2
8 5
2 2
Sample Output
1
4
0
Explanation
All possible values of and are:
The maximum possible value of that is also is , so we print on a new line.
Solution :
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int tc = 0; tc < T; tc++) {
int N = sc.nextInt();
int K = sc.nextInt();
System.out.println(solve(N, K));
}
sc.close();
}
static int solve(int N, int K) {
int result = 0;
for (int A = 1; A <= N; A++) {
for (int B = A + 1; B <= N; B++) {
int current = A & B;
if (current > result && current < K) {
result = current;
}
}
}
return result;
}
}
thanks bro for help me
ReplyDelete