## In-place swap

Write a function to swap a number in place without temporary variables.

My initial thoughts:
Before swap, ‘a’ points to number $a$ and ‘b’ points to number $b$.

1. ‘a’ points to ‘a’ – ‘b’, which is $a - b$.
2. ‘b’ points to ‘b’ + ‘a’, which is $b + (a - b) = a$.
3. ‘a’ points to ‘b’ – ‘a’, which is $a - (a - b) = b$.

My initial codes:

```void swap(int & a, int & b) {
a = a - b;
b = b + a;
a = b - a;
}

Solution:
void swap(int & a, int & b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}

^ is the exclusive-OR operator:

0^0=0
0^1=1
1^0=1
1^1=0

Hence, we have:

a=a^b: ‘a’ will save all the bits that $a$ differs from $b$: if the bit that ‘a’ and ‘b’ differ, it gets 1, otherwise 0.
b=a^b: ‘b’ will compare to the difference between $a$ and $b$: for the bit that ‘b’ and ‘a’ differ, it means $a$ have 1 at this position and the result of a^b will assign that bit to 1; for the bit that ‘b’ and ‘a’ agree, it means $a$ have 0 at this position and the result of a^b will assign that bit to 0.

a=a^b: Same logic.

div.wpmrec2x{max-width:610px;}
div.wpmrec2x div.u > div{float:left;margin-right:10px;}
div.wpmrec2x div.u > div:nth-child(3n){margin-right:0px;}

(function(g,\$){if("undefined"!=typeof g.__ATA){
}})(window,jQuery);

var o = document.getElementById('crt-1465569020');
if ("undefined"!=typeof Criteo) {
var p = o.parentNode;
p.style.setProperty('display', 'inline-block', 'important');
o.style.setProperty('display', 'block', 'important');
} else {
o.style.setProperty('display', 'none', 'important');
o.style.setProperty('visibility', 'hidden', 'important');
}

var o = document.getElementById('crt-850915282');
if ("undefined"!=typeof Criteo) {
var p = o.parentNode;
p.style.setProperty('display', 'inline-block', 'important');
o.style.setProperty('display', 'block', 'important');