- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Construct an array from GCDs of consecutive elements in given array in C++
- Unique element in an array where all elements occur k times except one in C++
- XOR of all Prime numbers in an Array in C++
- Sum of XOR of all pairs in an array in C++
- Minimizing array sum by applying XOR operation on all elements of the array in C++
- Maximum possible XOR of every element in an array with another array in C++
- Maximum value of XOR among all triplets of an array in C++
- Sum of XOR of sum of all pairs in an array in C++
- Find an integer X which is divisor of all except exactly one element in an array in C++
- How to sum elements at the same index in array of arrays into a single array? JavaScript
- XOR of all elements of array with set bits equal to K in C++
- Find elements of array using XOR of consecutive elements in C++
- Use an index array to construct a new array from a set of choices in Numpy
- Inserting element at falsy index in an array - JavaScript
- How to filter an array from all elements of another array – JavaScript?

Advertisements