Bitwise and (or &) of a range
Last Updated :
23 Jul, 2025
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.
Steps to implement-
- Initialize a variable res with the first number x
- Run a loop from x+1 to y
- In that loop store res & element of the loop into res
- Finally return/print res
Code-
C++
// 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)
{
// Initialize result as the first number
ll res = x;
// Traverse from x+1 to y
for (int i = x + 1; i <= y; i++) {
res = res & i;
}
return res;
}
// Driver code
int main()
{
ll x = 10, y = 15;
cout << andOperator(x, y);
return 0;
}
Java
// Java program to find bit-wise & of all
// numbers from x to y.
import java.io.*;
class GFG {
// Function to find Bit-wise & of along numbers from x
// to y.
static long andOperator(long x, long y)
{
// Initialize result as the first number
long res = x;
// Traverse from x+1 to y
for (long i = x + 1; i <= y; i++) {
res = res & i;
}
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 Utkarsh Kumar
Python3
# Function to find bitwise AND of all numbers from x to y
def and_operator(x, y):
# Initialize the result as the first number
res = x
# Traverse from x+1 to y
for i in range(x + 1, y + 1):
res = res & i
return res
# Driver code
if __name__ == "__main__":
x = 10
y = 15
print(and_operator(x, y))
C#
using System;
class GFG
{
// Function to find Bit-wise AND of all numbers from x to y.
static long AndOperator(long x, long y)
{
// Initialize result as the first number
long res = x;
// Traverse from x+1 to y
for (long i = x + 1; i <= y; i++)
{
res = res & i;
}
return res;
}
// Driver code
public static void Main(string[] args)
{
long x = 10, y = 15;
Console.Write(AndOperator(x, y));
}
}
JavaScript
//JavaScript program to find bit-wise & of all
// numbers from x to y.
// Function to find Bit-wise & of all numbers from x
// to y.
function andOperator(x, y)
{
// Initialize result as the first number
let res = x;
//Traverse from x+1 to y
for(let i=x+1;i<=y;i++){
res=res&i;
}
return res;
}
// Driver code
let x = 10, y = 15;
console.log(andOperator(x, y));
//This code is contributed by Tushar.
Time Complexity: O(y-x-1), because we have loop from x+1 to y
Auxiliary Space: O(1), because no extra space has been used
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++
// 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 2
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;
}
Java
// 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 2
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.
Python3
# 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 2
def 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 code
x, y = 10, 15
print(andOperator(x, y))
# This code is contributed by Anant Agarwal.
C#
// 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 2
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.
JavaScript
<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 2
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>
PHP
<?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 2
function 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
?>
Time Complexity: O(log(max(x, y)))
Auxiliary Space: O(1)
More efficient solution
- Flip the LSB of b.
- And check if the new number is in range(a < number < b) or not
- if the number greater than 'a' again flip lsb
- if it is not then that's the answer
C++
// 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 code
int main()
{
ll x = 10, y = 15;
cout << andOperator(x, y);
return 0;
}
Java
// An efficient Java program to find bit-wise & of all
// numbers from x to y.
import java.util.*;
class GFG {
// Function to find Bit-wise & of all numbers from x
// to y.
static int andOperator(int x, int y)
{
// Iterate over all bits of y, starting from the
// lsb, if it's equal to 1, flip it
for (int i = 0; i < (Math.log(y) / Math.log(2)) + 1;
i++) {
// repeat till x >= y, otherwise return the
// answer.
if (y <= x) {
return y;
}
if ((y & (1 << i)) != 0) {
y &= ~(1 << i);
}
}
return y;
}
// Driver code
public static void main(String[] args)
{
int x = 10;
int y = 15;
System.out.print(andOperator(x, y));
}
}
// This code is contributed by phasing17
Python3
# An efficient Python program to find bit-wise & of
# all numbers from x to y.
# Importing math module for using logarithm
import 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 code
x, y = 10, 15
print(andOperator(x, y))
# This code is contributed by Pushpesh Raj
C#
// An efficient C# program to find bit-wise & of all
// numbers from x to y.
using System;
class GFG {
// Function to find Bit-wise & of all numbers from x
// to y.
static int andOperator(int x, int y)
{
// Iterate over all bits of y, starting from the
// lsb, if it's equal to 1, flip it
for (int i = 0; i < (Math.Log(y) / Math.Log(2)) + 1;
i++) {
// repeat till x >= y, otherwise return the
// answer.
if (y <= x) {
return y;
}
if ((y & (1 << i)) != 0) {
y &= ~(1 << i);
}
}
return y;
}
// Driver code
public static void Main(string[] args)
{
int x = 10;
int y = 15;
Console.Write(andOperator(x, y));
}
}
// This code is contributed by phasing17
JavaScript
// An efficient JavaScript program to find bit-wise & of all
// numbers from x to y.
// Function to find Bit-wise & of all numbers from x
// to y.
function andOperator(x, y)
{
// Iterate over all bits of y, starting from the lsb, if it's equal to 1, flip it
for(var i=0; i<Math.log2(y)+1;i++)
{
//repeat till x >= y, otherwise return the answer.
if (y <= x) {
return y;
}
if (y & (1 << i)) {
y &= ~(1 << i);
}
}
return y;
}
// Driver code
var x = 10, y = 15;
console.log(andOperator(x, y));
//This code is contributed by phasing17
Time Complexity: O(log(y))
Auxiliary Space: O(1)
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 > 0
- Right shift a by 1 and right shift b by 1
- increment shiftcount
- after while loop return left * 2^(shiftcount)
C++
// 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 code
int32_t main() {
int a = 10, b = 15;
cout << andOperator(a, b);
return 0;
}
Java
// An efficient Java program to find bit-wise & of all
// numbers from x to y.
import java.util.*;
class GFG {
// Function to find Bit-wise & of all numbers from x
// to y.
static long 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 && a > 0) {
shiftcount++;
a = a >> 1;
b = b >> 1;
}
return (long)(a << shiftcount);
}
// Driver code
public static void main(String[] args)
{
int a = 10, b = 15;
System.out.println(andOperator(a, b));
}
}
// This code is contributed by phasing17
Python3
# 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 code
a, b =10, 15
print(andOperator(a, b))
# This code is contributed by Pushpesh Raj
C#
// An efficient C# program to find bit-wise & of all
// numbers from x to y.
using System;
class GFG
{
// Function to find Bit-wise & of all numbers from x
// to y.
static Int64 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 && a > 0)
{
shiftcount++;
a = a >> 1;
b = b >> 1;
}
return (Int64)(a << shiftcount);
}
// Driver code
public static void Main(string[] args) {
int a = 10, b = 15;
Console.WriteLine(andOperator(a, b));
}
}
// This code is contributed by phasing17
JavaScript
// An efficient JavaScript program to find bit-wise & of all
// numbers from x to y.
// Function to find Bit-wise & of all numbers from x
// to y.
function andOperator(a, b)
{
// ShiftCount variables counts till which bit every value 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(a != b && a > 0) {
shiftcount++;
a = a >> 1;
b = b >> 1;
}
return (a << shiftcount);
}
// Driver code
let a = 10, b = 15;
console.log(andOperator(a, b));
// This code is contributed by phasing17
Time Complexity: O(log(max(x, y)))
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem