Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
