Open In App

Bitwise AND of elements in range

Last Updated : 25 Nov, 2025
Comments
Improve
Suggest changes
29 Likes
Like
Report

Given two positive integers, l and r such that l ≤ r, find bit-wise AND of all integers from l to r, i.e., we need to compute value of l & (l+1) & ... & (r-1) & r, where & denotes bitwise AND.
Examples: 

Input: l = 10, r = 15
Output: 8
Explanation: 10 & 11 & 12 & 13 & 14 & 15 = 8

Input: l = 12, r = 15
Output: 12
Explanation: 12 & 13 & 14 & 15 = 12

[Naive Approach] Traversing all elements in range - O(y - x) Time and O(1) Space

We will start from l and keep AND-ing it with every next number (l+1, l+2, …, r). As we move forward, whenever any number in this range has a 0 in some bit position, that bit becomes 0 in the result. This continues until we reach r, giving the final AND of all numbers.

C++
//Driver Code Starts
#include <iostream>
using namespace std;

//Driver Code Ends

int andInRange(int l, int r) {
    
    // Initialize result as the first number
    int res = l;

    // Traverse from l+1 to r
    // and take the AND
    for (int i = l + 1; i <= r; i++) {
        res = res & i;
    }

    return res;
}

//Driver Code Starts

int main() {
    int l = 10, r = 15;
    cout << andInRange(l, r);
    return 0;
}

//Driver Code Ends
Java
//Driver Code Starts
class GFG {
    
//Driver Code Ends

    static int andInRange(int l, int r) {
        
        // Initialize result as the first number
        int res = l;

        // Traverse from x+1 to y
        // and take the AND
        for (int i = l + 1; i <= r; i++) {
            res = res & i;
        }

        return res;
    }

//Driver Code Starts
    
    public static void main(String[] args) {
        int l = 10, r = 15;
        System.out.print(andInRange(l, r));
    }
}
//Driver Code Ends
Python
def andInRange(l, r):
    
    # Initialize result as the first number
    res = l

    # Traverse from l+1 to r
    # and take the AND
    for i in range(l + 1, r + 1):
        res = res & i

    return res


#Driver Code Starts
if __name__ == "__main__":
    l = 10
    r = 15
    print(andInRange(l, r))

#Driver Code Ends
C#
//Driver Code Starts
using System;

class GFG {
    
//Driver Code Ends

    static int andInRange(int l, int r) {
        
        // Initialize result as the first number
        int res = l;

        // Traverse from l+1 to r
        // and take the AND
        for (int i = l + 1; i <= r; i++) {
            res = res & i;
        }

        return res;
    }

//Driver Code Starts

    public static void Main() {
        int l = 10, r = 15;
        Console.WriteLine(andInRange(l, r));
    }
}

//Driver Code Ends
JavaScript
function andInRange(l, r) {

    // Initialize result as the first number
    let res = l;

    // Traverse from l+1 to r
    // and take the AND
    for (let i = l + 1; i <= r; i++) {
        res = res & i;
    }

    return res;
}


//Driver Code Starts
// Driver code
let l = 10, r = 15;
console.log(andInRange(l, r));

//Driver Code Ends

Output
8

[Expected Approach - 1] Checking For All Bits - O(log r) Time and O(1) Space

The idea is to check each bit independently and decide whether that bit can stay 1 in the final AND. A bit remains 1 only if every number from l to r has that bit set. So for bit k, we first ensure that both l and r have that bit as 1. Next, we check whether the range crosses the boundary where that bit flips from 1 to 0.

This boundary appears at multiples of 2k, because below 2k the k-th bit is 0 and above it the k-th bit becomes 1. If the range size is smaller than 2k, we do not cross this boundary, so every number keeps that bit set. In that case, we can safely include that bit in the final result.

C++
//Driver Code Starts
#include <iostream>
#include <cmath>  

using namespace std;

//Driver Code Ends

int andInRange(int l, int r) {
    int andInRange = 0;

    int maxSetBit = (int)(log(r) / log(2));

    // for each bit check if it 
    // will be set in the AND of range
    for (int bit = 0; bit <= maxSetBit; bit++) {
        int andWithR = (r & (1 << bit));
        int andWithL = (l & (1 << bit));

        // if bit is set in l and r
        if (andWithR > 0 && andWithL > 0) {

            // if the numbers in range
            // from l to r <= 2^k
            if (r - l + 1 <= ((1 << bit)))
                andInRange = andInRange | (1 << bit);
        }
    }
    
    return andInRange;
}

//Driver Code Starts

int main() {
    int l = 10, r = 15;
    cout << andInRange(l, r);
    return 0;
}

//Driver Code Ends
Java
//Driver Code Starts
class GFG {
    
//Driver Code Ends

    static int andInRange(int l, int r) {
        int andInRange = 0;
        
        int maxSetBit = (int) (Math.log(r) / Math.log(2));
       
        // for each bit check if it 
        // will be set in the AND of range
        for( int bit = 0; bit <= maxSetBit; bit++ ) {
            int andWithR = (r & (1<<bit));
            int andWithL = (l & (1<<bit));
            
            // if bit is set in l and r
            if(andWithR > 0 && andWithL > 0) {
                
                // if the numbers in range
                // from l to r <= 2^k
                if(r-l+1 <= ((1<<bit)))
                    andInRange = andInRange | (1<<bit);
            } 
        }
        
        return andInRange;
    }

//Driver Code Starts
    
    public static void main(String[] args) {
        int l = 10, r = 15;
        System.out.print(andInRange(l, r));
    }
}
//Driver Code Ends
Python
#Driver Code Starts
import math

#Driver Code Ends

def andInRange(l, r):
    andInRange = 0

    maxSetBit = int(math.log(r, 2))

    # for each bit check if it 
    # will be set in the AND of range
    for bit in range(maxSetBit + 1):
        andWithR = (r & (1 << bit))
        andWithL = (l & (1 << bit))

        # if bit is set in l and r
        if andWithR > 0 and andWithL > 0:

            # if the numbers in range
            # from l to r <= 2^k
            if r - l + 1 <= (1 << bit):
                andInRange = andInRange | (1 << bit)

    return andInRange

#Driver Code Starts

if __name__ == "__main__":
    l, r = 10, 15
    print(andInRange(l, r))

#Driver Code Ends
C#
//Driver Code Starts
using System;

class GFG {
    
//Driver Code Ends

    static int andInRange(int l, int r) {
        int andInRange = 0;

        int maxSetBit = (int)(Math.Log(r) / Math.Log(2));

        // for each bit check if it 
        // will be set in the AND of range
        for (int bit = 0; bit <= maxSetBit; bit++) {

            int andWithR = (r & (1 << bit));
            int andWithL = (l & (1 << bit));

            // if bit is set in l and r
            if (andWithR > 0 && andWithL > 0) {

                // if the numbers in range
                // from l to r <= 2^k
                if (r - l + 1 <= (1 << bit))
                    andInRange = andInRange | (1 << bit);
            }
        }

        return andInRange;
    }

//Driver Code Starts

    static void Main() {
        int l = 10, r = 15;
        Console.Write(andInRange(l, r));
    }
}

//Driver Code Ends
JavaScript
function andInRange(l, r) {
    let andInRange = 0;

    let maxSetBit = Math.floor(Math.log(r) / Math.log(2));

    // for each bit check if it 
    // will be set in the AND of range
    for (let bit = 0; bit <= maxSetBit; bit++) {
        let andWithR = (r & (1 << bit));
        let andWithL = (l & (1 << bit));

        // if bit is set in l and r
        if (andWithR > 0 && andWithL > 0) {

            // if the numbers in range
            // from l to r <= 2^k
            if (r - l + 1 <= (1 << bit))
                andInRange = andInRange | (1 << bit);
        }
    }
    
    return andInRange;
}


//Driver Code Starts
// Driver code
let l = 10, r = 15;
console.log(andInRange(l, r));
//Driver Code Ends

Output
8

[Expected Approach - 2] Checking MSB - O(log r) Time and O(1) Space

The idea is that the AND of all numbers from l to r preserves only those higher-order bits where l and r are identical. We scan bits from the most significant bit downward. If both l and r have bit k set, then every number in the interval must lie inside the same block of size 2^(k+1) where bit k stays 1, so we safely keep that bit in the answer.

But if at some bit position one of l or r has the bit set and the other has it unset, it means the range crosses the boundary where bit k flips from 1 to 0. This boundary occurs every 2^k numbers. When the interval crosses such a boundary, there must be at least one number inside the range with that bit equal to 0. Once that happens, not only does bit k drop to 0 in the final AND, but all lower bits also lose their stability because they flip even more frequently. Therefore every bit below k is guaranteed to become 0, so we stop processing further.

C++
//Driver Code Starts
#include <iostream>
#include <cmath> 

using namespace std;

//Driver Code Ends

int andInRange(int l, int r) {
    int andInRange = 0;

    int maxSetBit = (int)(log(r) / log(2));
        
    // for each bit check if it 
    // will be set in the AND of range
    for (int bit = maxSetBit; bit >= 0; bit--) {
        int andWithR = (r & (1 << bit));
        int andWithL = (l & (1 << bit));

        // if bit is set in l and r
        if (andWithR > 0 && andWithL > 0) {

            // update the AND in range
            andInRange = andInRange | (1 << bit);
        }
        
        // if the bit is set in l and unset in r
        // then all bits lesser than bit will be unset in AND
        else if (andWithR > 0 || andWithL > 0)
            break;
    }
    return andInRange;
}

//Driver Code Starts

int main() {
    int l = 10, r = 15;
    cout << andInRange(l, r);
    return 0;
}

//Driver Code Ends
Java
//Driver Code Starts
class GFG {
    
//Driver Code Ends

    static int andInRange(int l, int r) {
        int andInRange = 0;
        
        int maxSetBit = (int) (Math.log(r) / Math.log(2));
        
        // for each bit check if it 
        // will be set in the AND of range
        for( int bit = maxSetBit; bit >= 0; bit-- ) {
            int andWithR = (r & (1<<bit));
            int andWithL = (l & (1<<bit));
            
            // if bit is set in l and r
            if(andWithR > 0 && andWithL > 0 ) {
                
                // update the AND in range
                andInRange = andInRange | (1<<bit);
            } 
            
            // if the bit is set in l and unset in r
            // then all bits lesser than bit will be unset in AND
            else if( andWithR > 0 || andWithL > 0 ) 
                break;
        }
        
        return andInRange;
    }

//Driver Code Starts
    
    public static void main(String[] args) {
        int l = 10, r = 15;
        System.out.print(andInRange(l, r));
    }
}
//Driver Code Ends
Python
#Driver Code Starts
import math

#Driver Code Ends

def andInRange(l, r):
    andInRange = 0

    maxSetBit = int(math.log(r, 2))

    # for each bit check if it 
    # will be set in the AND of range
    for bit in range(maxSetBit, -1, -1):
        andWithR = (r & (1 << bit))
        andWithL = (l & (1 << bit))

        # if bit is set in l and r
        if andWithR > 0 and andWithL > 0:

            # update the AND in range
            andInRange = andInRange | (1 << bit)

        # if the bit is set in l and unset in r
        # then all bits lesser than bit will be unset in AND
        elif andWithR > 0 or andWithL > 0:
            break

    return andInRange

#Driver Code Starts

if __name__ == "__main__" :
    l, r = 10, 15
    print(andInRange(l, r))

#Driver Code Ends
C#
//Driver Code Starts
using System;

class GFG {
    
//Driver Code Ends

    static int andInRange(int l, int r) {
        int andInRange = 0;

        int maxSetBit = (int)(Math.Log(r) / Math.Log(2));

        // for each bit check if it 
        // will be set in the AND of range
        for (int bit = maxSetBit; bit >= 0; bit--) {
            int andWithR = (r & (1 << bit));
            int andWithL = (l & (1 << bit));

            // if bit is set in l and r
            if (andWithR > 0 && andWithL > 0) {

                // update the AND in range
                andInRange = andInRange | (1 << bit);
            }
            
            // if the bit is set in l and unset in r
            // then all bits lesser than bit will be unset in AND
            else if (andWithR > 0 || andWithL > 0)
                break;
        }

        return andInRange;
    }

//Driver Code Starts

    static void Main() {
        int l = 10, r = 15;
        Console.Write(andInRange(l, r));
    }
}

//Driver Code Ends
JavaScript
function andInRange(l, r) {
    let andInRange = 0;

    let maxSetBit = Math.floor(Math.log(r) / Math.log(2));

    // for each bit check if it 
    // will be set in the AND of range
    for (let bit = maxSetBit; bit >= 0; bit--) {
        let andWithR = (r & (1 << bit));
        let andWithL = (l & (1 << bit));

        // if bit is set in l and r
        if (andWithR > 0 && andWithL > 0) {

            // update the AND in range
            andInRange = andInRange | (1 << bit);
        }
        
        // if the bit is set in l and unset in r
        // then all bits lesser than bit will be unset in AND
        else if (andWithR > 0 || andWithL > 0)
            break;
    }

    return andInRange;
}


//Driver Code Starts
// Driver code
let l = 10, r = 15;
console.log(andInRange(l, r));

//Driver Code Ends

Output
8

[Expected Approach - 3] Right Shifting Until l and r become equal - O(log l) Time and O(1) Space

The idea is that the AND of all numbers from l to r keeps only the bits where l and r share the same prefix. As long as l and r differ, some number in the range will force those lower bits to become 0. So we repeatedly right-shift both l and r until they become equal, which removes all unstable lower bits. The number of shifts tells us how many lower bits must be zero in the final answer. Once they match, we left-shift back to place the common prefix in its correct position, giving the AND of the whole range.

C++
//Driver Code Starts
#include <iostream>

using namespace std;

//Driver Code Ends

int andInRange(int l, int r) {

    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 (l != r && l > 0) {
        shiftCount++;
        l = l >> 1;
        r = r >> 1;
    }

    return (l << shiftCount);
}

//Driver Code Starts

int main() {
    int l = 10, r = 15;
    cout << andInRange(l, r);
    return 0;
}
//Driver Code Ends
Java
//Driver Code Starts
class GFG {
//Driver Code Ends

    static int andInRange(int l, int r){
    
        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 (l != r && l > 0) {
            shiftCount++;
            l = l >> 1;
            r = r >> 1;
        }
        return (l << shiftCount);
    }

//Driver Code Starts

    // Driver code
    public static void main(String[] args) {
        int l = 10, r = 15;
        System.out.println(andInRange(l, r));
    }
}
//Driver Code Ends
Python
def andInRange(l, r):

    # ShiftCount variables counts till
    # which bit every bit value that 
    # is not set in l or r will convert to 0
    shiftCount = 0

    # Iterate through every bit of a and b
    # simultaneously if l == r then we know that beyond
    # that the AND value will remain constant
    while l != r and l > 0:
        shiftCount += 1
        l = l >> 1
        r = r >> 1

    return (l << shiftCount)


#Driver Code Starts

if __name__ == "__main__" :
    l, r = 10, 15
    print(andInRange(l, r))
#Driver Code Ends
C#
//Driver Code Starts
using System;

class GFG {
//Driver Code Ends

    static int andInRange(int l, int r) {

        // ShiftCount variables counts till
        // which bit every bit value that 
        // is not set in l or r 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 (l != r && l > 0) {
            shiftCount++;
            l = l >> 1;
            r = r >> 1;
        }

        return (l << shiftCount);
    }

//Driver Code Starts

    public static void Main() {
        int l = 10, r = 15;
        Console.WriteLine(andInRange(l, r));
    }
}

//Driver Code Ends
JavaScript
function andInRange(l, r) {

    // ShiftCount variables counts till
    // which bit every bit value that 
    // is not set in l or r will convert to 0
    let 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 (l !== r && l > 0) {
        shiftCount++;
        l = l >> 1;
        r = r >> 1;
    }

    return (l << shiftCount);
}


//Driver Code Starts
// Driver code
let l = 10, r = 15;
console.log(andInRange(l, r));

//Driver Code Ends

Output
8



Article Tags :

Explore