What does bitwise XOR (exclusive OR) mean?

前端 未结 8 1302
眼角桃花
眼角桃花 2020-12-02 05:52

I\'m trying to understand the binary operators in C# or in general, in particular ^ - exclusive or.

For example:

Given an array of positive intege

8条回答
  •  暖寄归人
    2020-12-02 06:29

    This is based on the simple fact that XOR of a number with itself results Zero.

    and XOR of a number with 0 results the number itself.

    So, if we have an array = {5,8,12,5,12}.

    5 is occurring 2 times. 8 is occurring 1 times. 12 is occurring 2 times.

    We have to find the number occurring odd number of times. Clearly, 8 is the number.

    We start with res=0 and XOR with all the elements of the array.

    int res=0; for(int i:array) res = res ^ i;

        1st Iteration: res = 0^5 = 5
        2nd Iteration: res = 5^8 
        3rd Iteration: res = 5^8^12
        4th Iteration: res = 5^8^12^5 = 0^8^12 = 8^12
        5th Iteration: res = 8^12^12 = 8^0 = 8
    

提交回复
热议问题