Swap Two Numbers

Implement swapTwoNumbers

Given two integers a and b, return them swapped — [b, a] — without using a third variable to hold either value temporarily. XOR gives a way to swap in place: a ^= b changes a into a ^ b; b ^= a then changes b into b ^ (a ^ b), which simplifies to the original a; and a final a ^= b changes a into (a ^ b) ^ (original a), which simplifies to the original b. Three XOR operations, two variables, nothing extra needed.

Example 1:

Input: a = 5, b = 10

Output: [10,5]

Example 2:

Input: a = -3, b = 8

Output: [8,-3]

Example 3:

Input: a = 5, b = 5

Output: [5,5]

+ 7 hidden test cases run on Submit.

Constraints:

  • -2³¹ ≤ a, b ≤ 2³¹ − 1

a =

5

b =

10