Problem · Bit Manipulation
Swap Two Integers Without a Temporary Variable
Learn this problemProblem statement
Given two signed 32-bit integers a and b, swap their values without using a third scalar variable.
Return a two-element array [a, b] containing the values after the swap. The returned array is only the output representation; the swapping steps themselves must not store either value in a temporary scalar variable.
Function
swapWithoutTemporary(a: int, b: int) → int[]Examples
Example 1
a = 30b = 40return = [40,30]After the swap, a contains 40 and b contains 30.
Example 2
a = -7b = 12return = [12,-7]The same operation works when one value is negative.
Example 3
a = 5b = 5return = [5,5]Swapping equal values leaves the pair unchanged.
Constraints
-2147483648 <= a <= 2147483647-2147483648 <= b <= 2147483647- Do not use a third scalar variable to hold either input value during the swap.