Search code examples
c++algorithmxorbitmask

Why the following xor operation is resulting the wrong answer?


#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> input = {2,3,4,5,4,3,7,2};
    int XOR = 0;

    for (auto& i : input)
    {
      XOR = XOR ^ i;
    }
    return XOR;
}

This returns 2, when it should return 5. Can anyone please explain why?


Solution

  • [...] returns 2, when it should return 5. Can anyone please explain why?

    Add some debug lines, and you will see what is happening inside. With the help of std::format you can even see the binary representation of each XOR and i directly in each iteration. https://gcc.godbolt.org/z/Te1786j5j

    #include <format>  // std::format
    
    int iter{ 1 };
    for (const auto& i : input)
    {
        std::cout << std::format("Iteration {} : XOR {:03b} ^ i {:03b} = ", iter++, XOR, i);
        // For binary representations -------------> ^^^^^^     ^^^^^^   
        XOR = XOR ^ i;
        std::cout << std::format("{:03b}\n", XOR);
    }
    

    Prints:

    Iteration 1 : XOR 000 ^ i 010 = 010
    Iteration 2 : XOR 010 ^ i 011 = 001
    Iteration 3 : XOR 001 ^ i 100 = 101
    Iteration 4 : XOR 101 ^ i 101 = 000
    Iteration 5 : XOR 000 ^ i 100 = 100
    Iteration 6 : XOR 100 ^ i 011 = 111
    Iteration 7 : XOR 111 ^ i 111 = 000
    Iteration 8 : XOR 000 ^ i 010 = 010
    

    Now you see, it shouldn't be 5(i.e 101), rather 2 (i.e. 010).