Swap Without Temp Variable

Easy~10 min

Given two integers a and b, return them swapped as an array [b, a] using XOR bit manipulation. Do not use a temporary variable.

For example, given a = 3 and b = 5, return [5, 3].

Examples

Example 1
Input: a = 3, b = 5
Output: [5, 3]
Explanation: After swapping, a becomes 5 and b becomes 3.
Example 2
Input: a = 10, b = 20
Output: [20, 10]
Explanation: After swapping, a becomes 20 and b becomes 10.
Example 3
Input: a = 0, b = 7
Output: [7, 0]
Explanation: Swap works correctly even when one value is 0.

Constraints

  • -10^9 <= a, b <= 10^9
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run