Find XOR of all elements in an Array
Given an array arr[] containing integers of size N, the task is to find the XOR of this array.
Examples:
Input: arr[] = {2, 4, 7}
Output: 1
Explanation:
XOR of the array = 2 ^ 4 ^ 7 = 1
Input: arr[] = { 3, 9, 12, 13, 15 }
Output: 4
Approach: In order to find the XOR of all elements in the array, we simply iterate through the array and find the XOR using ‘^’ operator. 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.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
int xorOfArray( int arr[], int n)
{
int xor_arr = 0;
for ( int i = 0; i < n; i++) {
xor_arr = xor_arr ^ arr[i];
}
return xor_arr;
}
int main()
{
int arr[] = { 3, 9, 12, 13, 15 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << xorOfArray(arr, n) << endl;
return 0;
}
|
C
#include <stdio.h>
int xorOfArray( int arr[], int n)
{
int xor_arr = 0;
for ( int i = 0; i < n; i++) {
xor_arr = xor_arr ^ arr[i];
}
return xor_arr;
}
int main()
{
int arr[] = { 3, 9, 12, 13, 15 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "%d\n" , xorOfArray(arr, n));
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG {
static int xorOfArray( int arr[], int n)
{
int xor_arr = 0 ;
for ( int i = 0 ; i < n; i++) {
xor_arr = xor_arr ^ arr[i];
}
return xor_arr;
}
public static void main (String[] args)
{
int arr[] = { 3 , 9 , 12 , 13 , 15 };
int n = arr.length;
System.out.println(xorOfArray(arr, n));
}
}
|
Python3
def xorOfArray(arr, n):
xor_arr = 0
for i in range (n):
xor_arr = xor_arr ^ arr[i]
return xor_arr
if __name__ = = '__main__' :
arr = [ 3 , 9 , 12 , 13 , 15 ]
n = len (arr)
print (xorOfArray(arr, n))
|
C#
using System;
class GFG {
static int xorOfArray( int []arr, int n)
{
int xor_arr = 0;
for ( int i = 0; i < n; i++) {
xor_arr = xor_arr ^ arr[i];
}
return xor_arr;
}
public static void Main ( string [] args)
{
int []arr = { 3, 9, 12, 13, 15 };
int n = arr.Length;
Console.WriteLine(xorOfArray(arr, n));
}
}
|
Javascript
<script>
function xorOfArray(arr, n)
{
let xor_arr = 0;
for (let i = 0; i < n; i++) {
xor_arr = xor_arr ^ arr[i];
}
return xor_arr;
}
let arr = [ 3, 9, 12, 13, 15 ];
let n = arr.length;
document.write(xorOfArray(arr, n) + "<br>" );
</script>
|
Time Complexity: O(N), where N is the size of the array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Last Updated :
04 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...