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++
#include <bits/stdc++.h>
using namespace std;
int find_K( int K, vector< int >& arr)
{
int XOR = 0;
for ( int i = 0; i < arr.size(); i++)
XOR ^= arr[i];
return XOR ^ K;
}
int main()
{
int K = 4;
vector< int > arr = { 1, 4, 5, 6 };
cout << find_K(K, arr);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int find_K( int K, int arr[])
{
int XOR = 0 ;
for ( int i = 0 ; i < arr.length; i++)
XOR ^= arr[i];
return XOR ^ K;
}
public static void main(String[] args)
{
int K = 4 ;
int arr[] = { 1 , 4 , 5 , 6 };
System.out.print(find_K(K, arr));
}
}
|
Python3
def find_K(K, arr):
XOR = 0
for i in range ( len (arr)):
XOR ^ = arr[i]
return XOR ^ K
K = 4
arr = [ 1 , 4 , 5 , 6 ]
print (find_K(K, arr))
|
C#
using System;
class GFG
{
static int find_K( int K, int [] arr)
{
int XOR = 0;
for ( int i = 0; i < arr.Length; i++)
XOR ^= arr[i];
return XOR ^ K;
}
public static int Main()
{
int K = 4;
int [] arr = new int [] { 1, 4, 5, 6 };
Console.Write(find_K(K, arr));
return 0;
}
}
|
Javascript
<script>
const find_K = (K, arr) => {
let XOR = 0;
for (let i = 0; i < arr.length; i++)
XOR = (XOR ^ arr[i]);
return (XOR ^ K);
}
let K = 4;
let arr = [1, 4, 5, 6];
document.write(find_K(K, arr));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
02 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...