XOR and minus seems to be about the same in concept, because, as if “A-B” means “difference between A and B”, A^B also means “bitwise difference between A and B”.

Let’s see following two SWAP algorithm. (Analysing following alogrithm will be helpful to understand difference of concept between ‘A-B’ and ‘A^B’).

**add swap**

*x = *x + *y;

*y = *x – *y;

*x = *x – *y;

**xor swap**

*x ^= *y;

*y ^= *x;

*x ^= *y;

We should focus on that both of ‘-‘ and XOR are operation to get “difference”.

(‘-‘ is difference of number and XOR is bitwise difference. But, those are all “difference”!)

So, we can implement swap operation with both ‘-‘ and “XOR”.

Here is conceptual description of XOR swap.

*x ^= *y; “Store difference of ‘original x’ and ‘original y'”

*y ^= *x; “We know difference of ‘original x’ and ‘original y'(x). So, we can get ‘original x’ with ‘original y’ and store it into ‘y’.”

*x ^= *y; “We know difference of ‘original x’ and ‘original y'(x), and ‘orignal x'(y). So, we can get ‘original y’ and store it into ‘x’.”

Understanding something is “Understanding it’s basic concept”. It’s very important.!!

So, someone who understands XOR, should be able to infer “swap with XOR” at the moment of knowing about “swap with ‘+/-‘”

### Like this:

Like Loading...

*Related*