HackerRank Day 29 Solution in Python: Bitwise AND

Today we will see the HackerRank Day 29 Solution in Python. The problem is named Bitwise AND which is part of 30 Days of code on HackerRank. Let’s get started!

Day 29: Bitwise AND Problem statement

We are a given set and our task is to find two integers, A and B from the set such that the value of A&B is the maximum possible and less than a given integer, K . In this case, & represents the bitwise AND operator.

Sample Input

3       
5 2     
8 5     
2 2     

Sample Output

1
4
0

Explanation: The maximum possible value of A&B, which is lesser than K is found and we print on a new line.

You can solve the problem here.

HackerRank Day 29 Solution in Python

#!/bin/python3

import math
import os
import random
import re
import sys

#Function to find A&B
def bitwiseAnd(N, K):
    max_val = 0
    for i in range(K-2,N):
        for j in range(i+1,N+1):
            val = i&j
            if val == K-1:
                return val
            if max_val<val<K:
                max_val = val
    return max_val

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input().strip())

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

        count = int(first_multiple_input[0])

        lim = int(first_multiple_input[1])

        res = bitwiseAnd(count, lim)

        fptr.write(str(res) + '\n')

    fptr.close()

Code Explanation

  • First, we create a function bitwiseAnd to find the required output given in the problem statement
  • Then we created a variable max_value to store the maximum value found by A&B
  • After each check, the value is checked whether it is greater than max_value and less than k. If so, then max_value is updated
  • Finally, after all the iterations, max_value is returned

Also Read:

Share:

Author: Ayush Purawr