
- 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 XOR value of a pair from a range in C++
Problem statement
Given a range [L, R], we need to find two integers in this range such that their XOR is maximum among all possible choices of two integers
If the given range is L = 1 and R = 21 then the output will be 31 as − 31 is XOR of 15 and 16 and it is maximum within range.
Algorithm
1. Calculate the (L^R) value 2. From most significant bit of this value add all 1s to get the final result
Example
#include <bits/stdc++.h> using namespace std; int getMaxXOR(int L, int R){ int LXR = L ^ R; int msbPos = 0; while (LXR) { msbPos++; LXR >>= 1; } int maxXOR = 0; int two = 1; while (msbPos--) { maxXOR += two; two <<= 1; } return maxXOR; } int main(){ int L = 1; int R = 21; cout << "Result = " << getMaxXOR(L, R) << endl; return 0; }
Output
When you compile and execute the above program. It generates the following output −
Result = 31
- Related Articles
- Maximum Bitwise AND pair from given range in C++
- Minimum XOR Value Pair in C++
- Maximum XOR value in matrix in C++
- Find Maximum XOR value of a sub-array of size k 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++
- Maximum bitwise AND value of a pair in an array in C++
- Find a value whose XOR with given number is maximum in C++
- Maximum value of XOR among all triplets of an array in C++
- Get Random value from a range of numbers in JavaScript?
- Get a value from Pair Tuple class in Java
- Queries to find maximum product pair in range with updates in C++
- Probability of a random pair being the maximum weighted pair in C++
- Find the Number Whose Sum of XOR with Given Array Range is Maximum using C++
- Arrange a binary string to get maximum value within a range of indices C/C++?

Advertisements