Bitwise AND problem solution | 30 days of code | HackerRank

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
Output Format
For each test case, print the maximum possible value of  on a new line.
Bitwise AND problem solution | 30 days of code | HackerRank

Problem solution in Java programming language.

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();
    }
}


Problem solution in Python programming language.

#!/bin/python3

import math
import os
import random
import re
import sys

def max_bit(n,k):
    maximum = 0
    for i in range(1,n+1):
        for j in range(1,i):
            h = i & j
            if maximum < h < k:
                maximum = h
            if maximum == k-1:
                return maximum
    return maximum

if __name__ == '__main__':
    t = int(input())

    for t_itr in range(t):
        nk = input().split()

        n = int(nk[0])

        k = int(nk[1])
        
        print(max_bit(n,k))

Post a Comment

0 Comments