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:
let x: number = 3;
let y: number = 6;
x = x ^ y;
y = y ^ x;
x = x ^ y;
console.log(`x=${x}, y=${y}`);
Output:
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.