Construct an array from XOR of all elements of array except element at same index in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A[] with n positive elements. We have to create another array B, such that B[i] is XOR of all elements of A[] except A[i]. So if the A = [2, 1, 5, 9], then B = [13, 14, 10, 6]

To solve this, at first we have to find the XOR of all elements of A, and store it into variable x, then for each element of A[i], find B[i] = x XOR A[i]

Example

 Live Demo

#include <iostream>
using namespace std;
void findXOR(int A[], int n) {
   int x = 0;
   for (int i = 0; i < n; i++)
   x ^= A[i];
   for (int i = 0; i < n; i++)
   A[i] = x ^ A[i];
}
int main() {
   int A[] = {2, 1, 5, 9};
   int n = sizeof(A) / sizeof(A[0]);
   cout << "Actual elements: ";
   for (int i = 0; i < n; i++)
   cout << A[i] << " ";
   cout << endl;
   cout << "After XOR elements: ";
   findXOR(A, n);
   for (int i = 0; i < n; i++)
   cout << A[i] << " ";
}

Output

Actual elements: 2 1 5 9
After XOR elements: 13 14 10 6
raja
Published on 30-Dec-2019 14:42:25
Advertisements