Tuesday, 24 April 2012

Swap two numbers without using a temporary variable

It is a common question in interviews which involve some algorithmic or programmatic requirements. Even though this logic has got nothing much to do in the real world programming, it helps to check the ability of a candidate to form simple logic.
Swapping two numbers means interchanging the value present in the two variables. Normally it can be done using a third variable using the following algorithm.


a = 5;
b = 10;

temp = a;
a = b;
b = temp;

Now the values in a and b will be interchanged. The challenge is to get the same result without using any extra variable. To do this, use the following algorithm.

a = 5;
b = 10;

a = a + b;
b = a - b;
a = a - b;

Now the values are interchanged. Try the above with a few more examples to get a proper idea. This algorithm can be implemented using any programming language according to the requirement.
Now this can be done using multiplication and division instead of addition and subtraction using the following algorithm.

a = 5;
b = 10;

a = a * b;
b = a / b;
a = a / b;

The limitation when using multiplication and division is that the values cannot be zero. If either of the values are zero, you will get the wrong results.

1 comment:

  1. Thanks, I think there's also a solution using XOR that is discussed here as well:

    http://www.programmerinterview.com/index.php/general-miscellaneous/swap-numbers-without-temp/

    ReplyDelete