Given two non-negative long integers, x and y given x <= y, the task is to find bit-wise and of all integers from x and y, i.e., we need to compute value of x & (x+1) & … & (y-1) & y.7

Examples:

Input : x = 12, y = 15 Output : 12 12 & 13 & 14 & 14 = 12 Input : x = 10, y = 20 Output : 0

A **simple solution** is to traverse all numbers from x to y and do bit-wise and of all numbers in range.

An **efficient solution** is to follow following steps.

1) Find position of Most Significant Bit (MSB) in both numbers.

2) If positions of MSB are different, then result is 0.

3) If positions are same. Let positions be msb_p.

……a) We add 2^{msb_p} to result.

……b) We subtract 2^{msb_p} from x and y,

……c) Repeat steps 1, 2 and 3 for new values of x and y.

Example 1 :x = 10, y = 20 Result is initially 0. Position of MSB in x = 3 Position of MSB in y = 4 Since positions are different, return result.Example 2 :x = 17, y = 19 Result is initially 0. Position of MSB in x = 4 Position of MSB in y = 4 Since positions are same, we compute 2^{4}. We add 2^{4}to result. Result becomes 16. We subtract this value from x and y. New value of x = x - 2^{4}= 17 - 16 = 1 New value of y = y - 2^{4}= 19 - 16 = 3 Position of MSB in new x = 1 Position of MSB in new y = 2 Since positions are different, we return result.

// An efficient C++ program to find bit-wise & of all // numbers from x to y. #include<bits/stdc++.h> using namespace std; typedef long long int ll; // Find position of MSB in n. For example if n = 17, // then position of MSB is 4. If n = 7, value of MSB // is 3 int msbPos(ll n) { int msb_p = -1; while (n) { n = n>>1; msb_p++; } return msb_p; } // Function to find Bit-wise & of all numbers from x // to y. ll andOperator(ll x, ll y) { ll res = 0; // Initialize result while (x && y) { // Find positions of MSB in x and y int msb_p1 = msbPos(x); int msb_p2 = msbPos(y); // If positions are not same, return if (msb_p1 != msb_p2) break; // Add 2^msb_p1 to result ll msb_val = (1 << msb_p1); res = res + msb_val; // subtract 2^msb_p1 from x and y. x = x - msb_val; y = y - msb_val; } return res; } // Driver code int main() { ll x = 10, y = 15; cout << andOperator(x, y); return 0; }

Output:

8

This article is contributed by **Shivam Pradhan (anuj_charm)**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.