Problem · Bit Manipulation

Swap Two Numbers Without a Third Variable

Learn this problem
Easyinfosys logoinfosysNEW GRADONSITE INTERVIEW

Problem statement

Given two signed integers, first and second, swap their values without using a third variable to store either original value.

Return a two-element array containing the swapped values in the order [second, first]. The returned array is the output container; it is not a temporary variable for performing the swap.

Function

swapNumbers(first: int, second: int) → int[]

Examples

Example 1

first = 5second = -2return = [-2,5]

After the swap, first holds -2 and second holds 5, so the returned array is [-2, 5].

Example 2

first = 9second = 9return = [9,9]

The two input values are equal, so swapping them leaves the ordered pair unchanged.

Constraints

  • -2^31 <= first <= 2^31 - 1
  • -2^31 <= second <= 2^31 - 1
  • Do not use an additional variable to store either original value while performing the swap.

More infosys problems

drafts saved locally
public int[] swapNumbers(int first, int second) {
    // write your code here
}
first5
second-2
expected[-2,5]
checking account