Thursday, July 9, 2009

Swaping two values without using any third variable

Hello,
many times in interviews, A quesion is being asked that "How to swap two values with out using thrid variable".

We know how to swap using thrid vaiable i.e.
a=10;
b=20;
c=0;

c=a;
a=b;
b=c;

Now, if you want to swap two string variables without using third variable use

string A= "string A";
string B= "string B";

A+=b;
B = A.substring(0,A.Length-B.Length);
A = A.substring(B.Length);

in order to swap two integer values you can do the same as

int a = 10;
int b = 20;

A = A+B;
B = A-B;
A = A-B;

OR

A = A ^ B;
B = A ^ B;
A = A ^ B;

but there are exception in using the first option in swaping integer values. second will always give you the result, but sometimes first will result in over/under flow.

check it yourself.