Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Construct an array from XOR of all elements of array except element at same index in C++
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
#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
Advertisements