- Related Questions & Answers
- The Maximum Data Rate of a Channel
- How can I generate random number in a given range in Android?
- Why does Java strictly specify the range and behavior of its primitive types?
- Binary array after M range toggle operations?
- All possible co-prime distinct element pairs within a range [L, R]?
- Print N lines of numbers such that every pair among numbers has a GCD K
- Print missing elements that lie in range 0 – 99
- C++ Program for Range sum queries without updates?
- C/C++ Program for Maximum height when coins are arranged in a triangle?
- Selecting records within a range and with a condition set on two columns in MySQL?
- Get the maximum count of distinct values in a separate column with MySQL
- How to get the data associated with the maximum id in a MySQL table?
- Getting the maximum value from a varchar field in MySQL
- Finding the minimum and maximum value from a string with numbers separated by hyphen in MySQL?
- How to find a value between range in MySQL?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

1. Calculate the (L^R) value 2. From most significant bit of this value add all 1s to get the final result

#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; }

When you compile and execute the above program. It generates the following output −

Result = 31

Advertisements