Skip to content

swap variable quest

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,

A,B=B,A

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.

Solution:

A=A XOR B;
B=A XOR B;
A=A XOR B;

Explanation:
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.

Categories: Uncategorized.

Comment Feed

5 Responses

  1. I Have another logic for swaping two variables without using temperary variable..
    :)
    LET A=10 AND B=20
    A=A+B // A=10+20–> A=30
    B=A-B // B=30-20 —> B=10
    A=A-B // A=30-10 –>A=20

    :)
    SIMPLE RIGHT…

    Mohan K HJune 1, 2007 @ 6:12 pm
  2. Mohan K H:
    Yeah that’s the simple answer :D

  3. what ever u all said is right but all will failed when the any of them or ( A or B ) is equal to UINT_MAX or INT_MAX or if there addition cross the MAX_LIMIT of integer

    rajeshwarJune 5, 2007 @ 7:08 pm
  4. For the XOR example, even A or B is equal to UINT_MAX will not fail.

  5. even if you overflow with the + – method it will not fail, if overflow and underflow on your architecture do not produce signals and are consistent. (like if you used unsigned numbers). the overflows and underflows cancel out.

    OrangeTideJune 20, 2007 @ 6:29 am



Some HTML is OK

or, reply to this post via trackback.