Add an element in Array to make the bitwise XOR as K
Given an array arr[] containing N positive integers, the task is to add an integer such that the bitwise Xor of the new array becomes K.
Examples:
Input: arr[] = {1, 4, 5, 6}, K = 4
Output: 2
Explanation: Bit-wise XOR of the array is 6.
And bit-wise XOR of 6 and 2 is 4.Input: arr[] = {2, 7, 9, 1}, K = 5
Output: 8
Approach: The solution to the problem is based on the following idea of bitwise Xor:
If for two numbers X and Y, the bitwise Xor of X and Y is Z then the bitwise Xor of X and Z is Y.
Follow the steps to solve the problem:
- Let the bitwise XOR of the array elements be X.
- Say the required value to be added is Y such that X Xor Y = K.
- From the above observation, it is clear that the value to be added (Y) is the same as X Xor K.
Below is the implementation of the above approach:
C++
// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to find the required valueint find_K(int K, vector<int>& arr){ int XOR = 0; // Find XOR of all the array elements for (int i = 0; i < arr.size(); i++) XOR ^= arr[i]; // K = XOR^N, where N is size of array return XOR ^ K;} // Drivers codeint main(){ int K = 4; vector<int> arr = { 1, 4, 5, 6 }; // Function call cout << find_K(K, arr); return 0;} |
Output
2
Time Complexity: O(N)
Auxiliary Space: O(1)


