Hackerrank - Bit Manipulation - AND Product

Consider two non-negative long integers, a and b, where a<= b. The bitwise AND of all long integers in the inclusive range between a and b can be expressed as a & (a + 1) & ... & (b - 1) & b, where & is the bitwise AND operator.


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

Sample Input
3 
12 15 
2 3 
8 13

Sample Output
12 
2 
8

Explanation
There are three pairs to compute results for:

  1. a = 12 and  b = 15
    12 & 13 & 14 & 15 = 12, so we print 12 on a new line.
Solution
# Enter your code here. Read input from STDIN. Print output to STDOUT
for i in xrange(input()):
    a,b = [bin(int(i)) for i in raw_input().split()]
    a,b = a[2:],b[2:]
    for j,k in enumerate(a):
        if b[j] == "1" and k == "0":
            print int("0b"+a[:j]+"0"*(len(a)-j),2)
            break

Comments

Best Programming language for machine learning.

Popular posts from this blog

Hackerrank - Dynamic Programming - The Coin Change Problem

Hackerrank - Implementation - Picking Numbers