Bitwise and (or &) of a range - GeeksforGeeks

24 Mar, 2022
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 & 15 = 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 2msb_p to result. ......b) We subtract 2msb_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 24.

We add 24 to result. 
Result becomes 16.

We subtract this value from x and y.
New value of x  = x - 24  = 17 - 16 = 1
New value of y  = y - 24  = 19 - 16 = 3

Position of MSB in new x = 1
Position of MSB in new y = 2
Since positions are different, we return result.
 
C++
Java
Python3
C#
PHP
Javascript
// 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 3int 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 codeint main(){    ll x = 10, y = 15;    cout << andOperator(x, y);    return 0;}
// An efficient Java program to find bit-wise// & of all numbers from x to y.class GFG {         // 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    static int msbPos(long n)    {                 int msb_p = -1;        while (n > 0) {            n = n >> 1;            msb_p++;        }                 return msb_p;    }     // Function to find Bit-wise & of all    // numbers from x to y.    static long andOperator(long x, long y)    {                 long res = 0; // Initialize result         while (x > 0 && y > 0) {                         // 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            long 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    public static void main(String[] args)    {                 long x = 10, y = 15;                 System.out.print(andOperator(x, y));    }} // This code is contributed by Anant Agarwal.
# An efficient Python program to find# bit-wise & of all numbers from x to y. # Find position of MSB in n. For example# if n = 17, then position of MSB is 4.# If n = 7, value of MSB is 3def msbPos(n):     msb_p = -1    while (n > 0):             n = n >> 1        msb_p += 1         return msb_p # Function to find Bit-wise & of# all numbers from x to y.def andOperator(x, y):     res = 0 # Initialize result     while (x > 0 and y > 0):             # Find positions of MSB in x and y        msb_p1 = msbPos(x)        msb_p2 = msbPos(y)         # If positions are not same, return        if (msb_p1 != msb_p2):            break         # Add 2^msb_p1 to result        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 codex, y = 10, 15print(andOperator(x, y)) # This code is contributed by Anant Agarwal.
// An efficient C# program to find bit-wise & of all// numbers from x to y.using System; class GFG{    // 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    static int msbPos(long n)    {        int msb_p = -1;        while (n > 0)        {            n = n >> 1;            msb_p++;        }        return msb_p;    }         // Function to find Bit-wise    // & of all numbers from x    // to y.    static long andOperator(long x, long y)    {        // Initialize result        long res = 0;             while (x > 0 && y > 0)        {            // 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            long 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    public static void Main()    {        long x = 10, y = 15;        Console.WriteLine(andOperator(x, y));    }} // This code is contributed by Anant Agarwal.
<?php// An efficient C++ program// to find bit-wise & of all// numbers from x to y. // Find position of MSB in n.// For example if n = 17, then// position of MSB is 4. If n = 7,// value of MSB is 3function msbPos($n){    $msb_p = -1;    while ($n > 0)    {        $n = $n >> 1;        $msb_p++;    }    return $msb_p;} // Function to find Bit-wise &// of all numbers from x to y.function andOperator($x, $y){    $res = 0; // Initialize result     while ($x > 0 && $y > 0)    {        // Find positions of        // MSB in x and y        $msb_p1 = msbPos($x);        $msb_p2 = msbPos($y);         // If positions are not        // same, return        if ($msb_p1 != $msb_p2)            break;         // Add 2^msb_p1 to result        $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$x = 10;$y = 15;echo andOperator($x, $y); // This code is contributed// by ihritik?>
<script>    // Javascript program to find bit-wise// & of all numbers from x to y.     // 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    function msbPos(n)    {                   let msb_p = -1;        while (n > 0) {            n = n >> 1;            msb_p++;        }                   return msb_p;    }       // Function to find Bit-wise & of all    // numbers from x to y.    function andOperator(x, y)    {                   let res = 0; // Initialize result           while (x > 0 && y > 0) {                           // Find positions of MSB in x and y            let msb_p1 = msbPos(x);            let msb_p2 = msbPos(y);               // If positions are not same, return            if (msb_p1 != msb_p2)                break;               // Add 2^msb_p1 to result            let 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        let x = 10, y = 15;                   document.write(andOperator(x, y)); // This code is contributed by avijitmondal1998.</script>
8
More efficient solution  
Flip the LSB of b.And check if the new number is in range(a < number < b) or notif the number greater than ‘a’ again flip lsbif it is not then that’s the answer
Flip the LSB of b.
And check if the new number is in range(a < number < b) or notif the number greater than ‘a’ again flip lsbif it is not then that’s the answer
if the number greater than ‘a’ again flip lsb
if it is not then that’s the answer
C++
Python3
// 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;  // Function to find Bit-wise & of all numbers from x// to y.ll andOperator(ll x, ll y){    // Iterate over all bits of y, starting from the lsb, if it's equal to 1, flip it    for(int i=0; i<(int)log2(y)+1;i++)    {        //repeat till x >= y, otherwise return the answer.        if (y <= x) {            return y;        }        if (y & (1 << i)) {            y &= ~(1UL << i);        }    }    return y;} // Driver codeint main(){    ll x = 10, y = 15;    cout << andOperator(x, y);    return 0;}
# An efficient Python program to find bit-wise & of# all numbers from x to y. # Importing math module for using logarithmimport math # Function to find Bit-wise & of all numbers from x# to y.def andOperator(x, y):       # Iterate over all bits of y, starting from the lsb, if it's equal to 1, flip it    for i in range(int(math.log2(y) + 1)):               # repeat till x >= y, otherwise return the answer        if(y <= x):            return y        if(y & 1 << i):            y = y & (~(1<<i))    return y   # Driver codex, y = 10, 15print(andOperator(x, y)) # This code is contributed by Pushpesh Raj
8
Another Approach
We know that if a number num is a power of 2 then (num &(num – 1)) is equal to 0. So if a is less than 2^k  and b is greater than or equal to 2^k, then the & of all values in between a and b should be zero as (2^k & (2^k – 1)) is equal to 0. So, if both a and b lies within the same number of bits then only answer wont be zero. Now, in every case last bit is bound to be zero because even if a and b are 2 side by side numbers last bit will be different. Similarly 2nd last bit will be zero if difference between a and b is greater than 2 and this goes on for every bit. Now, take example a = 1100(12) and b = 1111(15), then last bit should be zero of the answer. For 2nd last bit we need to check whether a/2 == b/2 because if they are equal then we know that b – a <= 2. So if a/2 and b/2 is not equal then we proceed. Now, 3rd last bit should have a difference of 4 which can be checked by a/ 4 != b/4. Hence we check every bit from last until a!=b and in every step we modify a/=2(a >> 1) and b/=2(b >> 1) to reduce a bit from end.
Run a while loop as long as a != b and a > 0Right shift a by 1 and right shift b by 1increment shiftcountafter while loop return left * 2^(shiftcount)
Run a while loop as long as a != b and a > 0
Right shift a by 1 and right shift b by 1
increment shiftcount
after while loop return left * 2^(shiftcount)
C++
Python3
// An efficient C++ program to find bit-wise & of all// numbers from x to y.#include<bits/stdc++.h>using namespace std;#define int long long int // Function to find Bit-wise & of all numbers from x// to y.int andOperator(int a, int b) {      // ShiftCount variables counts till which bit every value will convert to 0      int shiftcount = 0;    //Iterate through every bit of a and b simultaneously      //If a == b then we know that beyond that the and value will remain constant      while(a != b and a > 0) {          shiftcount++;          a = a >> 1;          b = b >> 1;    }      return int64_t(a << shiftcount);} // Driver codeint32_t main() {    int a = 10, b = 15;    cout << andOperator(a, b);    return 0;}
# An efficient Python program to find bit-wise & of# all numbers from x to y. # Function to find Bit-wise & of all numbers from x# to y.def andOperator(a,b):         # ShiftCount variables counts till which bit every value will convert to 0    shiftcount=0         # Iterate through every bit of a and b simultaneously    # If a == b then we know that beyond that the and value will remain constant    while(a!=b and a>0):        shiftcount=shiftcount+1        a=a>>1        b=b>>1             return a<<shiftcount# Driver codea, b =10, 15print(andOperator(a, b)) # This code is contributed by Pushpesh Raj
Bibhu Pala
ihritik
SHUBHAMSINGH10
nayansachdeva7361
ApurvaRaj
avijitmondal1998
moumenhamada30
longcodex
pushpeshrajdx01
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Cyclic Redundancy Check and Modulo-2 Division
Binary representation of a given number
Program to find whether a given number is power of 2
Add two numbers without using arithmetic operators
Set, Clear and Toggle a given bit of a number in C
Josephus problem | Set 1 (A O(n) Solution)
Bit Fields in C
Find the element that appears once
1's and 2's complement of a Binary Number