65.9K
CodeProject is changing. Read more.
Home

Swaping values of two variable without temporary variable

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (16 votes)

Mar 4, 2010

CPOL
viewsIcon

25954

I don't know whether these type of tips are allowed or not. But after having experience of core algorithm-base technical interview I thought I should share question I was asked in my interview.They asked me to show all methods I know to swap values of two variables.I Tried my level best...

I don't know whether these type of tips are allowed or not. But after having experience of core algorithm-base technical interview I thought I should share question I was asked in my interview. They asked me to show all methods I know to swap values of two variables. I Tried my level best to do it:
//1st method
a -= b;
b += a;         
a = (b - a);    

//2nd methos
a = b + a - (b = a)

//3rd method
a ^= b ^= a ^= b;

//4th method
a -= b += a -= b = -b;

//5th method
//Assuming a and b are none zero and int
a=a*b;
b=a/b;
a=a/b;

//6th method
//Assuming a and b are binary types
a %= b %= a %= b;
Note : All one line codes are compiler dependent only.