Click here to Skip to main content
11,502,812 members (46,617 online)
Click here to Skip to main content

Tagged as

Swaping values of two variable without temporary variable

, 11 Mar 2010 CPOL 12.6K 20
Rate this:
Please Sign up or sign in to vote.
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

chevu
Software Developer
India India
No Biography provided
Follow on   Twitter

Comments and Discussions

 
Questionmethod 2 is not working Pin
Sivaji156516-Mar-14 20:57
memberSivaji156516-Mar-14 20:57 
GeneralFastest One :) Pin
Vitaly Tomilov28-Aug-12 12:50
memberVitaly Tomilov28-Aug-12 12:50 
GeneralNice article, even in today's world it occurs rarely that on... Pin
nv319-Dec-11 22:26
membernv319-Dec-11 22:26 
Generalgood for tiny processors with limited RAM Pin
Harold Bamford16-Mar-10 11:45
memberHarold Bamford16-Mar-10 11:45 
GeneralRe: good for tiny processors with limited RAM Pin
chevu16-Mar-10 22:49
memberchevu16-Mar-10 22:49 
GeneralRe: good for tiny processors with limited RAM Pin
Pranit Kothari3-Jan-12 3:14
memberPranit Kothari3-Jan-12 3:14 
GeneralRe: good for tiny processors with limited RAM Pin
huangyi520921-Mar-11 0:23
memberhuangyi520921-Mar-11 0:23 
GeneralRe: good for tiny processors with limited RAM Pin
Pranit Kothari3-Jan-12 3:15
memberPranit Kothari3-Jan-12 3:15 
GeneralRe: good for tiny processors with limited RAM Pin
JackDingler14-Mar-12 4:51
memberJackDingler14-Mar-12 4:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 11 Mar 2010
Article Copyright 2010 by chevu
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid