给定数组arr [] ,任务是检查数组所有元素的总和是否等于数组所有元素的XOR。
例子:
Input: arr[] = [1, 2]
Output: YES
Explanation:
Sum = (1+2) = 3
XOR = (1^2) = 3
Input: arr[] = [6, 3, 7, 10]
Output: NO
Explanation:
Sum = (6 + 3 + 7 + 10) = 26
XOR = (6 ^ 3 ^ 7 ^ 10) = 8
方法:
- 遍历Array并找到所有元素的总和。
- 同样,对数组的所有元素进行XOR。
- 检查总和与异或值是否相等。
下面是上述方法的实现:
C++
// C++ Implementation to Check
// if Sum and XOR of all Elements
// of Array is equal
#include
using namespace std;
// Function to Check if Sum and XOR
// of all elements of array is equal
int equal_xor_sum(int arr[], int n)
{
int Sum = 0;
int Xor = 0;
// Sum and XOR of all elements
for (int i = 0; i < n; i++) {
Sum = Sum + arr[i];
Xor = Xor ^ arr[i];
}
// Checking Sum and XOR to be equal
if (Sum == Xor)
cout << "YES";
else
cout << "NO";
return 0;
}
// Driver Function
int main()
{
int arr[] = { 6, 3, 7, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
// Check Sum and XOR is equal
equal_xor_sum(arr, n);
return 0;
}
Java
// Java Implementation to Check
// if Sum and XOR of all Elements
// of Array is equal
class GFG
{
// Function to Check if Sum and XOR
// of all elements of array is equal
static void equal_xor_sum(int arr[], int n)
{
int Sum = 0;
int Xor = 0;
// Sum and XOR of all elements
for (int i = 0; i < n; i++)
{
Sum = Sum + arr[i];
Xor = Xor ^ arr[i];
}
// Checking Sum and XOR to be equal
if (Sum == Xor)
System.out.println("YES");
else
System.out.println("NO");
}
// Driver Function
public static void main (String[] args)
{
int arr[] = { 6, 3, 7, 10 };
int n = arr.length;
// Check Sum and XOR is equal
equal_xor_sum(arr, n);
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 Implementation to Check
# if Sum and XOR of all Elements
# of Array is equal
# Function to Check if Sum and XOR
# of all elements of array is equal
def equal_xor_sum(arr, n) :
Sum = 0;
Xor = 0;
# Sum and XOR of all elements
for i in range(n) :
Sum = Sum + arr[i];
Xor = Xor ^ arr[i];
# Checking Sum and XOR to be equal
if (Sum == Xor) :
print("YES");
else :
print("NO");
# Driver Function
if __name__ == "__main__" :
arr = [ 6, 3, 7, 10 ];
n = len(arr);
# Check Sum and XOR is equal
equal_xor_sum(arr, n);
# This code is contributed by AnkitRai01
C#
// C# Implementation to Check
// if Sum and XOR of all Elements
// of Array is equal
using System;
class GFG
{
// Function to Check if Sum and XOR
// of all elements of array is equal
static void equal_xor_sum(int []arr, int n)
{
int Sum = 0;
int Xor = 0;
// Sum and XOR of all elements
for (int i = 0; i < n; i++)
{
Sum = Sum + arr[i];
Xor = Xor ^ arr[i];
}
// Checking Sum and XOR to be equal
if (Sum == Xor)
Console.WriteLine("YES");
else
Console.WriteLine("NO");
}
// Driver Function
public static void Main()
{
int []arr = { 6, 3, 7, 10 };
int n = arr.Length;
// Check Sum and XOR is equal
equal_xor_sum(arr, n);
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
NO
时间复杂度: O(n)