C++ Program to find Number Whose XOR Sum with Given Array is a Given Number k

C++Server Side ProgrammingProgramming

To solve a problem in which, given, we are tasked to find the number such that the XOR sum of a given array with that number becomes equal to k, for example.

Input: arr[] = {1, 2, 3, 4, 5}, k = 10
Output: 11
Explanation: 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 11 = 10

Input: arr[] = { 12, 23, 34, 56, 78 }, k = 6
Output: 73

In this program, we are going to use the property of xor if A^B = C and A^C = B, and we are going to apply this in this problem.

Approach to Find the Solution

In this approach, we will use the above property of the xor operator now. For this problem, now we traverse through the array, and then if we xor the number with k, that will be our answer.


C++ Code for the Above Approach

#include <bits/stdc++.h>
using namespace std;
int main(){
    int arr[] = { 1, 2, 3, 4, 5 }; // given array
    int n = sizeof(arr) / sizeof(int); // size of our array
    int k = 10; // given k
    int answer = 0;
    for(int i = 0; i < n; i++) // traversing the array for
       // xor sum
       answer ^= arr[i];

    answer ^= k; // XORing with k to get our answer
    cout << answer << "\n"; // printing our answer
    return 0;



Explanation for the Above Approach

In this approach, we are going to use some property of xor operator, so for that, we are simply going to traverse through the array and then find the xor sum of the whole array, and then we xor that xor sum with k and that answer and then we print our answer.


In this tutorial, we solve finding the Number whose XOR sum with a given array is a given number k. We also learned the C++ program for this problem and the complete approach (Normal) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this tutorial helpful.

Published on 25-Nov-2021 09:34:19