Bit Manipulation Bit basics
107. Swap Without a Temp
You are given two integers a and b. Swap their values without using a third variable, then return
[a, b].
After the swap, a holds the value b had, and b holds the value a had. So the answer is the
original b followed by the original a.
The usual swap first copies one value into a temporary variable. Here, only a and b may hold values
while you swap them. Building the returned pair at the end is fine.
Example 1
Input: a = 17, b = -4
[-4,17]Explanation: After the swap, a holds −4 and b holds 17.
Example 2
Input: a = 9, b = 9
[9,9]Explanation: Equal values are allowed. Swapping them gives the same pair.
Example 3
Input: a = -2147483648, b = 2147483647
[2147483647,-2147483648]Explanation: The smallest and the largest 32-bit integers trade places like any other pair.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
-231 ≤ a, b ≤ 231 − 1
Clarifying questions
What you would ask an interviewer before writing any code.