Click here to Skip to main content
Click here to Skip to main content

Tagged as

Swaping values of two variable without temporary variable

, 11 Mar 2010 CPOL
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 PinmemberSivaji156516-Mar-14 20:57 
AnswerRe: method 2 is not working PinmemberGarrylg10-Apr-14 9:25 
GeneralRe: method 2 is not working PinmemberSivaji156510-Apr-14 22:39 
GeneralFastest One :) PinmemberVitaly Tomilov28-Aug-12 12:50 
GeneralNice article, even in today's world it occurs rarely that on... Pinmembernv319-Dec-11 22:26 
Generalgood for tiny processors with limited RAM PinmemberHarold Bamford16-Mar-10 11:45 
GeneralRe: good for tiny processors with limited RAM Pinmemberchevu16-Mar-10 22:49 
GeneralRe: good for tiny processors with limited RAM PinmemberPranit Kothari3-Jan-12 3:14 
GeneralRe: good for tiny processors with limited RAM Pinmemberhuangyi520921-Mar-11 0:23 
GeneralRe: good for tiny processors with limited RAM PinmemberPranit Kothari3-Jan-12 3:15 
GeneralRe: good for tiny processors with limited RAM PinmemberJackDingler14-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 | Mobile
Web01 | 2.8.141015.1 | Last Updated 11 Mar 2010
Article Copyright 2010 by chevu
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid