Search code examples
stringalgorithmduplicatesbit-manipulationxor

The use of XOR for removing character from string and finding duplicates


The following questions are based on the use of XOR :

  1. Given a string say of integers. The task at hand is to remove the given character from string. I tried using XOR to solve it. eg char str[] = "123456" . Remove 4. XOR the given character with the entire string. That character vanishes.

    XOR = (1^2^3^4^5^6) ^ 4
    

    However I am left with the XOR of the remaining characters.

    XOR = (1^2^3^5^6)
    

    Is there any method I could get the individual characters back?

  2. I need to find and remove elements that have duplicates (including the elements themselves)

    eg. A = {1,9,8,2,2} then output should be {1,9,8} after removal

    However this will fail since 1^9 = 8. Hence (1^9)^8^2^2 gives empty array. Is there any alternative using XOR itself?


Solution

  • int num=4;
    for(i=0;i<strlen(str);i++)
    {
        if(((str[i]-'0')^num) == 0)
            remove_number(i);
    }