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

**My initial thoughts:**

Before swap, ‘a’ points to number and ‘b’ points to number .

- ‘a’ points to ‘a’ – ‘b’, which is .
- ‘b’ points to ‘b’ + ‘a’, which is .
- ‘a’ points to ‘b’ – ‘a’, which is .

**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;
}

Comments:

^ is the exclusive-OR operator:

Hence, we have:

- a=a^b: ‘a’ will save all the bits that differs from : if the bit that ‘a’ and ‘b’ differ, it gets 1, otherwise 0.
- b=a^b: ‘b’ will compare to the difference between and : for the bit that ‘b’ and ‘a’ differ, it means 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 have 0 at this position and the result of a^b will assign that bit to 0.
- a=a^b: Same logic.

### Like this:

Like Loading...

*Related*