+ 3

Swap values without 3rd variable

Any two values can be swapped using a temporary 3rd variable. But how to do it using only the given values without using a 3rd variable? In any language

23rd May 2017, 2:58 AM
Deepesh Choudhary
Deepesh Choudhary - avatar
4 Antworten
+ 7
in other languages x=x+y y=x-y x=x-y in python x, y=y, x
23rd May 2017, 3:54 AM
Mayur Chaudhari
Mayur Chaudhari - avatar
+ 18
In Ruby it's as easy as in Python 😊: x, y = 7, 2 #assigning values x=7, y=2 x, y = y, x #swapping values x=y, y=x print x, y #prints 27
23rd May 2017, 4:21 AM
Pao
Pao - avatar
+ 13
x = x + y y = x - y x = x - y
23rd May 2017, 3:25 AM
Karl T.
Karl T. - avatar
+ 8
And this (xor swap), just to be complete for searchers (x and​ y must be at different memory addresses). x = x xor y y = x xor y x = x xor y
23rd May 2017, 5:53 AM
Kirk Schafer
Kirk Schafer - avatar