Check if the XOR of an array of integers is Even or Odd
Last Updated :
10 Nov, 2021
Given an array arr containing integers of size N, the task is to check if the XOR of this array is even or odd
Examples:
Input: arr[] = { 2, 4, 7}
Output: Odd
Explanation:
XOR of array = 2 ^ 4 ^ 7 = 1, which is odd
Input: arr[] = { 3, 9, 12, 13, 15 }
Output: Even
Naive Solution: First find the XOR of the given array of integers, and then check if this XOR is even or odd.
Time Complexity: O(N)
Efficient Solution: A better Solution is based on bit manipulation fact, that:
- Bitwise XOR of any two even or any two odd numbers is always even.
- Bitwise XOR of an even and an odd number is always odd.
Therefore if the count of odd numbers in the array is odd, then the final XOR will be odd and if it is even, then final XOR will be even.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string check( int arr[], int n)
{
int count = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] & 1)
count++;
}
if (count & 1)
return "Odd" ;
else
return "Even" ;
}
int main()
{
int arr[] = { 3, 9, 12, 13, 15 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << check(arr, n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static String check( int []arr, int n)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
if ((arr[i] & 1 )!= 0 )
count++;
}
if ((count & 1 )!= 0 )
return "Odd" ;
else
return "Even" ;
}
public static void main(String args[])
{
int []arr = { 3 , 9 , 12 , 13 , 15 };
int n = arr.length;
System.out.println(check(arr, n));
}
}
|
Python3
def check(arr, n):
count = 0 ;
for i in range (n):
if (arr[i] & 1 ):
count = count + 1 ;
if (count & 1 ):
return "Odd" ;
else :
return "Even" ;
if __name__ = = '__main__' :
arr = [ 3 , 9 , 12 , 13 , 15 ]
n = len (arr)
print (check(arr, n))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
static String check( int []arr, int n)
{
int count = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] == 1)
count++;
}
if (count == 1)
return "Odd" ;
else
return "Even" ;
}
public static void Main(String[] args)
{
int []arr= { 3, 9, 12, 13, 15 };
int n = arr.Length;
Console.Write(check(arr, n));
}
}
|
Javascript
<script>
function check(arr, n)
{
let count = 0;
for (let i = 0; i < n; i++)
{
if (arr[i] & 1)
count++;
}
if (count & 1)
return "Odd" ;
else
return "Even" ;
}
let arr = [ 3, 9, 12, 13, 15 ];
let n = arr.length;
document.write(check(arr, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...