HackerRank 30 Days Of Code Challenge, Day29(Ques 30 in Java)

 


Objective
Welcome to the last day! Today, we're discussing bitwise operations. Check out the Tutorial tab for learning materials and an instructional video!

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.

Function Description
Complete the bitwiseAnd function in the editor below.

bitwiseAnd has the following paramter(s):
int N: the maximum integer to consider
int K: the limit of the result, inclusive

Returns
int: the maximum value of  within the limit.

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.

Constraints

Sample Input

STDIN   Function
-----   --------
3       T = 3
5 2     N = 5, K = 2
8 5     N = 8, K = 5
2 2     N = 8, K = 5

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.


Answer:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for (int i = 0; i < q; i++) {
            int n = in.nextInt();
            int k = in.nextInt();

            int maxed = 0;
            for (int b = 2; b <= n; b++) {
                for (int a = 1; a < b; a++) {
                    if (a == b) continue;
                    int ab = a&b;
                    if (ab > maxed && ab < k) maxed = ab;
                }
            }
            System.out.println(maxed);
        }
    }
}


Now just submit the code and check the result.

Comments

Popular posts from this blog

C program to find the greatest of three numbers with user input.

How to add to integers in C programming