XOR of all the elements in the given range [L, R] in C++


In this problem, we are given two integer L and R denoting a range. Our task is to find xor of all elements within the range [L, R].

Let’s take an example to understand the problem,

Input − L=3, R = 6

Explanation − 3^4^5^6 =

To solve this problem, we will find the MSB of R. the MSB of the answer will not be greater than R. Now, we will find the parity of count of the number of bits from 0 to MSB.

Now, to find the parity count for an ith bit, we can see that the state of an ith bit will change on every 2ith number. The same is for all ith bit set in the range L to R. On doing this, two cases arise −

Case 1(i != 0) − Check ith bit of L. if it is set, check parity count of the number between L and L+2i. And if an ith bit of L is set, then L is odd, then the count is odd otherwise it is even. Now, we will move to R, and determine the parity of count of a number of elements between R-2i and R and follow the same method.

Rest all integers are not taken under consideration as they will generate even the number of an integer with ith bit set.

Case 2(i = 0) − here, we will have to consider the following case −

Case 2.1 − L and R both odd, count the number of integers with the 0th-bit set will be (R-L)/2+1.

Case 2.2 − Else, the count will be round down a number of (R-L+1)/2.

Example

Program to show the implementation of our solution,

 Live Demo

#include <iostream>
using namespace std;
int findMSB(int x) {
   int ret = 0;
   while ((x >> (ret + 1)) != 0)
      ret++;
   return ret;
}
int XOREleInRange(int L, int R) {
   int max_bit = findMSB(R);
   int mul = 2;
   int ans = 0;
   for (int i = 1; i <= max_bit; i++) {
      if ((L / mul) * mul == (R / mul) * mul) {
         if (((L & (1 << i)) != 0) && (R - L + 1) % 2 == 1)
            ans += mul;
         mul *= 2;
         continue;
      }
      bool oddCount = 0;
      if (((L & (1 << i)) != 0) && L % 2 == 1)
         oddCount = (oddCount ^ 1);
      if (((R & (1 << i)) != 0) && R % 2 == 0)
         oddCount = (oddCount ^ 1);
      if (oddCount)
         ans += mul;
      mul *= 2;
   }
   int zero_bit_cnt = zero_bit_cnt = (R - L + 1) / 2;
   if (L % 2 == 1 && R % 2 == 1)
      zero_bit_cnt++;
   if (zero_bit_cnt % 2 == 1)
      ans++;
   return ans;
}
int main(){
   int L = 1, R = 4;
   cout<<"The XOR of all element within the range ("<<L<<", "<<R<<") is : "<<XOREleInRange(L, R);
   return 0;
}

Output

The XOR of all element within the range (1, 4) is : 4

Updated on: 20-Apr-2020

515 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements