← DiffPush

Swap two numbers without temporary variable

Baseline Bit Manipulation · Learn Bit Manipulation O(1) · O(1)

The Dockhands' XOR Handshake

Two dockhands carry pallet tokens and need to trade them, but the dock forbids spare clipboards — no third hand allowed. The XOR handshake saves them: combining their tokens into one register, each worker can re-derive the other's token by XOR-ing the register against what they still hold. Three such handshakes leave every token in the other's grip.

Input: Two integers a and b.

Output: The pair [b, a] — the values after swapping.

Constraints

Examples

Example 1

Input: {"a":13,"b":9}
Output: [9,13]
Three XOR rounds exchange the values with no third storage slot.

Example 2

Input: {"a":5,"b":5}
Output: [5,5]
Equal tokens survive the handshake — the swap is its own identity here.

Solve this in your browser →

Also on LeetCode ↗