
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- How to calculate the XOR of array elements using JavaScript?
- Maximum sum of n consecutive elements of array in JavaScript
- Consecutive elements sum array in JavaScript
- Find consecutive elements average JavaScript
- Construct an array from GCDs of consecutive elements in given array in C++
- Absolute Difference of all pairwise consecutive elements in an array (C++)?
- JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array
- Check if array elements are consecutive in Python
- XOR of all elements of array with set bits equal to K in C++
- Compress array to group consecutive elements JavaScript
- Minimizing array sum by applying XOR operation on all elements of the array in C++
- Compute the differences between consecutive elements of a masked array in Numpy
- Construct an array from XOR of all elements of array except element at same index in C++
- Python – Summation of consecutive elements power
- Count of only repeated element in a sorted array of consecutive elements in C++

Advertisements