Three XOR - One of the two exchange a few methods

  • a = a ^ b;
    b = a ^ b;
    a = a ^ b;

 

  • Why three XOR operation can exchange two numbers

Essence: two of the binary numbers obtained in different numbers of bits, each negated

See: https://www.cnblogs.com/bsc2012/p/9260436.html

 

  • Exclusive use three or problems that need attention:

Reference: https://blog.csdn.net/qq792326645/article/details/47723487

When the two switching elements in the array, if the length of the array is odd, there will be the problem of the intermediate element is set to zero.

However, different objects, two elements of the same value of three exclusive-OR operation is not set to 0.

the reason:

The former is the same object, in a first operation is a = a ^ b, A is set to 0, the same address, so that b is also 0, the final result is 0.

The latter is set to a 0, does not affect the value of b, there is no problem.

Guess you like

Origin www.cnblogs.com/musecho/p/11550629.html