Find elements of array using XOR of consecutive elements in C++

C++Server Side ProgrammingProgramming

Consider we have to find a list of n elements. But we have the XOR value of two consecutive elements of the actual array. Also the first element of the actual is given. So if the array elements are a, b, c, d, e, f, then the given array will be a^b, b^c, c^d, d^e and e^f.

As the first number is given, named a, that can help us to find all numbers. If we want to find the second element of the actual array, then we have to perform b = a ^ arr[i], for second element c = b ^ arr[1] and so on.

Example

#include<iostream>
using namespace std;
void findActualElements(int a, int arr[], int n) {
   int actual[n + 1];
   actual[0] = a;
   for (int i = 0; i < n; i++) {
      actual[i + 1] = arr[i] ^ actual[i];
   }
   for (int i = 0; i < n + 1; i++)
      cout << actual[i] << " ";
}
int main() {
   int arr[] = { 12, 5, 26, 7 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int a = 6;
   findActualElements(a, arr, n);
}

Output

6 10 15 21 18
raja
Published on 01-Nov-2019 07:16:08
Advertisements