
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum Bitwise AND pair from given range in C++
Problem statement
Given a range [L, R], the task is to find a pair (X, Y) such that L ≤ X < Y ≤ R and X & Y is maximum among all the possible pairs then print the bitwise AND of the found pair.
Example
If L = 1 and R = 10 then maximum bitwise AND value is 8 which can be formed as follows −
1000 # Binary representation of 8 Bitwise AND 1001 # Binary representation of 9 ---- 1000 # Final result
Algorithm
Iterate from L to R and check the bitwise AND for every possible pair and print the maximum value in the ends
Example
Let us now see an example −
#include <bits/stdc++.h> using namespace std; int getMaxBitwiseAndValue(int L, int R) { int maxValue = L & R; for (int i = L; i < R; ++i) { for (int j = i + 1; j <= R; ++j) { maxValue = max(maxValue, (i & j)); } } return maxValue; } int main() { int L = 1, R = 10; cout << "Maximum value = " << getMaxBitwiseAndValue(L, R) << endl; return 0; }
Output
Maximum value = 8
- Related Articles
- Maximum bitwise AND value of a pair in an array in C++
- Maximum XOR value of a pair from a range in C++
- Program to find bitwise AND of range of numbers in given range in Python
- Bitwise AND of Numbers Range in C++
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python
- Bitwise and (or &) of a range in C++
- Find a pair from the given array with maximum nCr value in Python
- Find a pair from the given array with maximum nCr value in C++
- Queries to find maximum product pair in range with updates in C++
- Queries for bitwise AND in the index range [L, R] of the given Array using C++
- Maximum Subarray Sum in a given Range in C++
- Maximum prefix-sum for a given range in C++
- Bitwise OR (or - ) of a range in C++
- Queries for Bitwise OR in the Index Range [L, R] of the Given Array using C++
- Python – Maximum in Row Range

Advertisements