Type Here to Get Search Results !

Day 29: HackerRank 30 Days Of Code Solution by CodingHumans | Bitwise AND

0

Day 29: Bitwise AND

Problem

Objective

Hey CodingHumans Welcome to the last day! of HackerRank 30 days of code today, we're discussing bitwise operations.

Task

Given set S={1,2,3,4.....N} . Find two integers, A and B  (where ), from set S such that the value of A&B is the maximum possible and also less than a given integer, K . In this case,  & represents the bitwise AND operator.

Input Style

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

Constraints

1<= T <= 10^3
2<= N <=10^3
2<= K <=N

Output Style

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:

1.   A=1, B=2; A & B = 0
2.   A=1, B=3; A & B = 1
3.   A=1, B=4; A & B = 0
4.   A=1, B=5; A & B = 1
5.   A=2, B=3; A & B = 2
6.   A=2, B=4; A & B = 0
7.   A=2, B=5; A & B = 0
8.   A=3, B=4; A & B = 0
9.   A=3, B=5; A & B = 1
10. A=4, B=5; A & B = 4

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




Recommended: Please try your approach on your integrated development environment (IDE) first, before moving on to the solution.

Few words from CodingHumans : Don't Just copy paste the solution, try to analyze the problem and solve it without looking by taking the the solution as a hint or a reference . Your understanding of the solution matters.


HAPPY CODING 😁






Solution
( Java )


import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int t = scanner.nextInt();

        for (int tItr = 0; tItr < t; tItr++) {
            int n = scanner.nextInt();
            int k = scanner.nextInt();
            int res=0;
            for(int i=0;i<n;i++){
                for(int j=i+1;j<=n;j++){
                    int and=i&j;
                    if(and<k && and > res){
                        res=and;
                    }
                }
            }
           System.out.println(res);
            }  
             scanner.close(); 
          }
       
    }


If you have any doubts regarding this problem or  need the solution in other programming languages then leave a comment down below . 

Post a Comment

0 Comments

Top Post Ad

Below Post Ad