Cerinta completa

Consider two non-negative long integers, and , where . The bitwise AND of all long integers in the inclusive range between and can be expressed as , where is the bitwise AND operator.

Given pairs of long integers, and , compute and print the bitwise AND of all natural numbers in the inclusive range between and .

For example, if and , the calculation is .

Function Description

Complete the andProduct in the editor below. It should return the computed value as an integer.

andProduct has the following parameter(s):

  • a: an integer
  • b: an integer

Input Format

The first line contains a single integer , the number of intervals to test.
Each of the next lines contains two space-separated integers and .

Constraints

Output Format

For each pair of long integers, print the bitwise AND of all numbers in the inclusive range between and on a new line.

Sample Input 0

3
12 15
2 3
8 13

Sample Output 0

12
2
8

Explanation 0

There are three pairs to compute results for:

  1. and
    , so we print on a new line.
  2. and
  3. and

Sample Input 1

2
17 23
11 15

Sample Output 1

16
8

Limbajul de programare folosit: python3

Cod:

#!/bin/python3
# try bruteforce

import sys
from math import log2

def andProduct(a, b):
    if a == 0:
        return 0
    if int(log2(a)) != int(log2(b)):
        return 0
    else:
        res_bin = list(bin(a)[2:])
        len_res = len(res_bin)
        for ind, digit in enumerate(res_bin):
            if ind == 0 or digit == '0':
                continue
            else:
                #print("ind = {}".format(ind))
                test_bin = list(bin(b)[2:])
                #test_bin = list(res_bin)
                test_bin[ind] = '0'
                #print(test_bin)
                #print(1 << (len_res - ind))
                #test_dec = b & (((1 << (ind-1) ) | 1) << len_res - ind)
                #test_dec = (((1 << (ind-1) ) | 1) << len_res - ind)
                #test_dec = b & (((1 << (ind-1) ) | 1) << len_res - ind)
                #print("test_dec1 = {}".format(1 << (ind-1)))
                #print("test_dec2 = {}".format((1 << (ind-1)) | 1))
                test_dec = int("".join(test_bin), 2)
                #print("test_dec3 = {}".format(((1 << (ind-1)) | 1) << len_res - ind))
                if a <= test_dec <= b:
                    res_bin[ind] = '0'
        return int("".join(res_bin), 2)
            
if __name__ == "__main__":
    n = int(input().strip())
    for a0 in range(n):
        a, b = input().strip().split(' ')
        a, b = [int(a), int(b)]
        result = andProduct(a, b)
        print(result)

Scor obtinut: 1.0

Submission ID: 464605127

Link challenge: https://www.hackerrank.com/challenges/and-product/problem

AND Product