The Wayback Machine - https://web.archive.org/web/20220421102612/https://www.geeksforgeeks.org/add-an-element-in-array-to-make-the-bitwise-xor-as-k/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Add an element in Array to make the bitwise XOR as K

  • Last Updated : 21 Apr, 2022

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 value
int 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 code
int 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)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!