EN
TypeScript - XOR swap algorithm
0 points
In this short article, we would like to show how to make number variables swap using the XOR swap algorithm using TypeScript.
Hint: the motivation to use XOR swap is when we work on the divices that have limited operating memory - e.g. micro controllers.
Quick solution:
xxxxxxxxxx
1
let x: number = 3;
2
let y: number = 6;
3
4
x = x ^ y;
5
y = y ^ x;
6
x = x ^ y;
7
8
console.log(`x=${x}, y=${y}`);
Output:
xxxxxxxxxx
1
x=6, y=3
How does it work?
The XOR operation can be inverted - it means, we do not lose any information with that operation. By executing it 3 times we are able to change variable value places.