Check if Sum and XOR of all elements of array is equal
Last Updated :
21 Sep, 2022
Given an array arr[], the task is to check if sum of all elements of an array is equal to XOR of all elements of array.
Example:
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
Approach:
- Iterate over the Array and find sum of all elements.
- Similarly, XOR all the elements of the array.
- Check if sum and xor value is equal.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int equal_xor_sum( int arr[], int n)
{
int Sum = 0;
int Xor = 0;
for ( int i = 0; i < n; i++) {
Sum = Sum + arr[i];
Xor = Xor ^ arr[i];
}
if (Sum == Xor)
cout << "YES" ;
else
cout << "NO" ;
return 0;
}
int main()
{
int arr[] = { 6, 3, 7, 10 };
int n = sizeof (arr) / sizeof (arr[0]);
equal_xor_sum(arr, n);
return 0;
}
|
Java
class GFG
{
static void equal_xor_sum( int arr[], int n)
{
int Sum = 0 ;
int Xor = 0 ;
for ( int i = 0 ; i < n; i++)
{
Sum = Sum + arr[i];
Xor = Xor ^ arr[i];
}
if (Sum == Xor)
System.out.println( "YES" );
else
System.out.println( "NO" );
}
public static void main (String[] args)
{
int arr[] = { 6 , 3 , 7 , 10 };
int n = arr.length;
equal_xor_sum(arr, n);
}
}
|
Python3
def equal_xor_sum(arr, n) :
Sum = 0 ;
Xor = 0 ;
for i in range (n) :
Sum = Sum + arr[i];
Xor = Xor ^ arr[i];
if ( Sum = = Xor) :
print ( "YES" );
else :
print ( "NO" );
if __name__ = = "__main__" :
arr = [ 6 , 3 , 7 , 10 ];
n = len (arr);
equal_xor_sum(arr, n);
|
C#
using System;
class GFG
{
static void equal_xor_sum( int []arr, int n)
{
int Sum = 0;
int Xor = 0;
for ( int i = 0; i < n; i++)
{
Sum = Sum + arr[i];
Xor = Xor ^ arr[i];
}
if (Sum == Xor)
Console.WriteLine( "YES" );
else
Console.WriteLine( "NO" );
}
public static void Main()
{
int []arr = { 6, 3, 7, 10 };
int n = arr.Length;
equal_xor_sum(arr, n);
}
}
|
Javascript
<script>
function equal_xor_sum(arr, n)
{
let Sum = 0;
let Xor = 0;
for (let i = 0; i < n; i++) {
Sum = Sum + arr[i];
Xor = Xor ^ arr[i];
}
if (Sum === Xor)
document.write( "YES" );
else
document.write( "NO" );
}
let arr = [ 6, 3, 7, 10 ];
let n = arr.length;
equal_xor_sum(arr, n);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1) because it is using constant space for variables
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...