This is an interesting quest given by my friend who working in Intel, during our conversation online.
How to swap two variables ?
Let say A=123 and B=546, how to swap them. So this is a quest, be smart enough not to give a plain solution like create a temporary variable to swap them. First of all my answer sounds a bit stupid. I say if I coded in python,
Okay that is not the expecting answer. Before you look at the solution below, maybe you would like to try to figure out.
Hint: use logic XOR, no additional variable is needed.
A=A XOR B; B=A XOR B; A=A XOR B;
XOR is known as exclusive disjunction where the nature of XOR is when 1 XOR 0 will equal to 1 but when 1 XOR 1 will becomes 0. Another important behavior of XOR is when (a XOR b) XOR b will resulting a.
So lets look back at the solution, you will find A XOR B seems to become “something else”, where this “something else” will return A if we XOR B and return B if we XOR A. So first line, A=(A XOR B). Secondly B = (A XOR B) XOR B = A, where we replace the original A into (A XOR B). Last line, A= ( A XOR B) XOR A = B. Seems at second line B already become A, so we replace B as A.
Interesting isn’t it? Look at it few times, if you can’t get it.