+ 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
4 Respuestas
+ 7
in other languages
x=x+y
y=x-y
x=x-y
in python
x, y=y, x
+ 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
+ 13
x = x + y
y = x - y
x = x - y
+ 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