Bit Manipulation Bit basics

107. Swap Without a Temp

Easy

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

Output: [-4,17]

Explanation: After the swap, a holds −4 and b holds 17.

Example 2

Input: a = 9, b = 9

Output: [9,9]

Explanation: Equal values are allowed. Swapping them gives the same pair.

Example 3

Input: a = -2147483648, b = 2147483647

Output: [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.

a = -5, b = 0

Constraints

  • -231 ≤ a, b ≤ 231 − 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.