
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
Find Elements of Array Using XOR of Consecutive Elements in C++
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
Advertisements