给定一个包含大小为N的整数的数组arr ,任务是检查此数组的XOR是偶数还是奇数
例子:
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
天真的解决方案:首先找到给定整数数组的XOR,然后检查此XOR是偶数还是奇数。
时间复杂度: O(N)
高效的解决方案:更好的解决方案基于位操作事实,即:
- 任何两个偶数或任何两个奇数的按位XOR始终为偶数。
- 偶数和奇数的按位XOR始终为奇数。
因此,如果数组中奇数的计数为奇数,则最终的XOR将为奇数,如果为偶数,则最终的XOR将为偶数。
下面是上述方法的实现:
C++
// C++ program to check if the XOR
// of an array is Even or Odd
#include
using namespace std;
// Function to check if the XOR of
// an array of integers is Even or Odd
string check(int arr[], int n)
{
int count = 0;
for (int i = 0; i < n; i++) {
// Count the number
// of odd elements
if (arr[i] & 1)
count++;
}
// If count of odd elements
// is odd, then XOR will be odd
if (count & 1)
return "Odd";
// Else even
else
return "Even";
}
// Driver Code
int main()
{
int arr[] = { 3, 9, 12, 13, 15 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << check(arr, n) << endl;
return 0;
}
Java
// Java rogram to check if the XOR
// of an array is Even or Odd
import java.util.*;
class GFG{
// Function to check if the XOR of
// an array of integers is Even or Odd
static String check(int []arr, int n)
{
int count = 0;
for (int i = 0; i < n; i++) {
// Count the number
// of odd elements
if ((arr[i] & 1)!=0)
count++;
}
// If count of odd elements
// is odd, then XOR will be odd
if ((count & 1)!=0)
return "Odd";
// Else even
else
return "Even";
}
// Driver Code
public static void main(String args[])
{
int []arr = { 3, 9, 12, 13, 15 };
int n = arr.length;
// Function call
System.out.println(check(arr, n));
}
}
// This code is contributed by Surendra_Gangwar
Python3
# Python3 program to check if the XOR
# of an array is Even or Odd
# Function to check if the XOR of
# an array of integers is Even or Odd
def check(arr, n):
count = 0;
for i in range(n):
# Count the number
# of odd elements
if (arr[i] & 1):
count = count + 1;
# If count of odd elements
# is odd, then XOR will be odd
if (count & 1):
return "Odd";
# Else even
else:
return "Even";
# Driver Code
if __name__=='__main__':
arr = [ 3, 9, 12, 13, 15 ]
n = len(arr)
# Function call
print(check(arr, n))
# This code is contributed by Princi Singh
C#
// C# program to check if the XOR
// of an array is Even or Odd
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
// Function to check if the XOR of
// an array of integers is Even or Odd
static String check(int []arr, int n)
{
int count = 0;
for (int i = 0; i < n; i++) {
// Count the number
// of odd elements
if (arr[i] == 1)
count++;
}
// If count of odd elements
// is odd, then XOR will be odd
if (count == 1)
return "Odd";
// Else even
else
return "Even";
}
// Driver Code
public static void Main(String[] args)
{
int []arr= { 3, 9, 12, 13, 15 };
int n = arr.Length;
// Function call
Console.Write(check(arr, n));
}
}
// This code is contributed by shivanisinghss2110
输出:
Even
时间复杂度:O(N)