Adjacent xor code in python
View Discussion Show Improve Article Save Article View Discussion Improve Article Save Article Given a sequence arr[] of N-1 elements which is xor of all adjacent pairs in an array, the task is to find that
original array from the arr[].
Approach:
Let's the expected array be - {a, b, c, d, e} Then the XOR array for this array will be - {a^b, b^c, c^d, d^e} Now XOR of all the element from 1 to N - xor_all => a ^ b ^ c ^ d ^ e XOR of the adjacent elements - xor_adjacent => ((a ^ b) ^ (c ^ d)) Now the XOR of the both the array will be the last element of the expected permutation => (a ^ b ^ c ^ d ^ e) ^ ((a ^ b) ^ (c ^ d)) => As all elements are in pair except the last element. => (a ^ a ^ b ^ b ^ c ^ c ^ d ^ d ^ e) => (0 ^ 0 ^ 0 ^ 0 ^ e) => e
Below is the implementation of the above approach: C++
Java
Python3
C#
Javascript
Performance Analysis:
How do you find the XOR of consecutive elements in an array?Let a, b, c, d, e, f are the original elements, and the xor of every 2 consecutive elements is given, i.e a^b = k1, b ^ c = k2, c ^ d = k3, d ^ e = k4, e ^ f = k5 (where k1, k2, k3, k4, k5 are the elements that are given us along with the first element a), and we have to find the value of b, c, d, e, f.
How do you find the XOR of two arrays?Therefore, the following steps are followed to compute the answer: Create a variable to store the XOR of the array as a result. For each element in the array, find the XOR of the element and the result variable using '^' operator. Finally, the result variable stores the XOR of all elements in the array.
How do you do XOR between two numbers?To find the XOR of two numbers, follow these instructions:. Convert the numbers into the binary representation.. Compare the corresponding bits of the two numbers.. If only one of the input bits is true (1), the output is true (1). Otherwise, the output is false (0).. How does Python calculate XOR?In Python, bitwise operators are used to performing bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit, hence the name bitwise operators.
...
Bitwise operators.. |