Click here to Skip to main content
15,912,977 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hi guys, i have a problem here,

int X = 150;
int y = 45;

i must swap the two values without using a temporary variable.

result should be like this:

X = 45
and
y=150

any solutions guys., thanks
Posted

The classic way is to use XOR three times:

a ^= b;
b ^= a;
a ^= b;

Now go figure out why it works!
 
Share this answer
 
Here you go!
C++
int x = 10
int y = 20

x = x+y;
y = x-y;
x = x-y;

// Print swapped values!
cout << x    //20
cout << y    //10
 
Share this answer
 
I can think of a convoluted solution, which involves working out if each bit is different, and if it is, swapping them both. It seems like a retarded thing to do, however.
 
Share this answer
 
Comments
Sandeep Mewara 22-Jul-10 2:58am    
Actually this is an old question generally asked by tech people to check aptitude!

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900