Replacing a seat

how to swap two numbers without using any extra space?

+3
source share
4 answers

If you have 2 variables a and b : (each variable takes its own memory address)

a = a xor b
b = a xor b
a = a xor b


There are also some other options for this problem, but they will fail if there is an overflow:

a = a + b
B = AB
a = ab

a = a * b
b = a / b
a = a / b

The plus and minus changes can work if you have custom types that have + and - operators that make sense.


. , 1 2 , . .

, , 2 . , , .

.. :

int a = 3;
int b = 3;

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

assert(a == b);
assert(a == 3);
+3

XOR :

if( x != y) { // this check is very important.

  x ^= y;
  y ^= x;
  x ^= y;
}

EDIT:

. :

int x = 10;

, x , , x=0, .

, , .

+5

Xor trick - :

int x, y;
x ^= y;
y ^= x;
x ^= y;

xoring is significantly less clear than just using temp, but it fails if x and y are the same place

+3
source

Since langauge was not mentioned, in Python:

y, x = x, y

0
source

Source: https://habr.com/ru/post/1742058/


All Articles