利用异或实现两个数交换原理

异或基本性质:

  • 相同为 0, 不同为 1
  • x ^ x = 0
  • x ^ 0 = x

a, b交换

a = a ^ b
b = a ^ b
a = a ^ b

证:

(1) a = a ^ b   =>  a = a ^ b, b = b
(2) b = a ^ b  =>  a = a ^ b, b = a ^ b ^ b = a ^ 0 = a
(3) a = a ^ b  =>  a = a ^ b ^ a = b ^ 0 = b

备注:需考虑内存溢出

你可能感兴趣的:(利用异或实现两个数交换原理)