0^0 = 1^1 = 0
0^1 = 1^0 = 1
x^0 = x 且 x^x = 0
交换律:x^y = y^x
结合律:(xy)z = x(yz)
自反性:xyy = x
int swap(int &a,int &b)
{
a = a^b;
b = a^b;
a = a^b;
}
令
XOR(X)
表示将X集合内所有的数做异或XOR(B)^XOR(A) = XOR(B)XOR(B)x = 0^x = x
xor(A) = xyy…z^z = x(yy…z^z) = x^0 = x
相当于x出现了3次,xxx = x,
其他数出现了两次,x^x = 0
public int FindDuplicate(int[] nums) { int res = 0; for(int i = 0; i < nums.Length; i++){ res ^= nums[i]; res ^= i; } return res; }
原文:https://www.cnblogs.com/xiaoxiao179/p/13622682.html