简体   繁体   中英

C# Inverse Xor function

I've just got back from a C# technical interview/test, but was kind of stumped by one of the puzzles. Could somebody help with the solution as I can't work it out and its really bugging me. The problem was:

Write an inverse Xor function for the following method:

public int[] XorFunction(int[] array)
{
    for (int i = array.Length - 1; i > 0; i--)
    {
        int first = array[i];
        int second = array[i - 1];
        array[i] ^= second;
    }
    return array;
}

I'm more of a database guy, so not completely sure about Xoring functions. The clostest I came was to naively iterate [1..array.length], and setting array[i] ^= array[i+1], but I'm pretty sure that wasnt right as I'd be changing the value for array[i] and then using it to xor with the next number.

Its bugging me becuase it seems like quite a straight forward problem...

Not exactly sure what you're trying to do, the loop doesn't exactly make sense... ?

However, you can flip bits or 'inverse' the result with the ~ operator.

So, var a = ~(a ^ b);

Code:

public int[] UnXorFunction(int[] array)
{
    for (int i = 1; i < array.Length; ++i)
    {
        int v = array[i - 1];
        array[i] ^= v;
    }
    return array;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM