This page has been designed specifically for the printed screen. It may look different than the page you were viewing on the web.
Please recycle it when you're done reading.

The URI for this page is { http://cc.byexamples.com }

swap variable quest Posted on May 28th

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 bellow, 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.

Trackback URL

Some Responses to “swap variable quest” :

  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…

    Commented Mohan K H on June 1st, 2007.
  2. Mohan K H:
    Yeah that’s the simple answer :D

    Commented mysurface on June 2nd, 2007.
  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

    Commented rajeshwar on June 5th, 2007.
  4. For the XOR example, even A or B is equal to UINT_MAX will not fail.

    Commented mysurface on June 7th, 2007.
  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.

    Commented OrangeTide on June 20th, 2007.
Leave your own comments about this post: