My real purpose is to get the only array element that appears odd number of times. So I found out it can be done via XOR-ing all elements of the array. Like this:
int[] arr = { 3, 4, 7, 7, 0, 4, 0, 7, 3 };
Console.WriteLine(arr[0] ^ arr[1] ^ arr[2] ^ arr[3] ^ arr[4] ^ arr[5] ^ arr[6] ^ arr[7] ^ arr[8]);
The problem however is that the array is not given, but is being read from the console, thus I don't know how to XOR the elements after they are entered. The code I could work out so far is:
EDIT: I managed to finish the code properly, thanks to your help.
static void Main()
{
int N = int.Parse(Console.ReadLine());
long[] rectArray = new long[N];
for (int i = 0; i < N; i++)
{
rectArray[i] = long.Parse(Console.ReadLine());
}
long initial = rectArray[0];
for (int i = 1; i < rectArray.Length; ++i)
{
initial ^= rectArray[i];
}
Console.WriteLine(initial);
}
}
P.S I'm real noob, so please be patient! :)
Along the same lines as Esailija's answer, but using foreach
- taking advantage of the fact that 0 ^ x == x
for all values of x
:
int current = 0;
foreach (int value in array)
{
current ^= value;
}
Console.WriteLine(current);
EDIT: As noted in comments, LINQ's Aggregate
method will do this too - and as we're happy to use the first two values in the first step, we don't even need to provide a seed:
int xor = array.Aggregate((x, y) => x ^ y);
You could write a loop:
int initial = 0;
for( int i = 0; i < arr.Length; ++i ) {
initial ^= arr[i];
}
Console.WriteLine( initial );
for (int i = 0; i < rectArray.Length; i++)
{
sum ^= rectArray[i];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With