Swap two numbers without a third variable
EasyBasics5 min
Write a function swapPair(pair) that swaps two numbers without a third variable.
A function cannot change the variables of the code that called it, so the two numbers come in an array: pair is [a, b].
- Change
pairitself so that it becomes[b, a], then return that same array, not a new one. aandbare integers from-1000000000000to1000000000000. They can be negative, zero or equal.- No third variable: inside the function do not write
let,constorvar, do not add a second parameter, and do not write another function in it (its parameters would be variables too). - Keep values only in the two items of
pair: do not add items or properties to the array or to the function, and do not create a global variable (temp = pair[0]withoutletcreates one).
Examples
swapPair([1, 2])Returns [ 2, 1 ]
swapPair([-5, 0])Returns [ 0, -5 ]
Check yourself
- No helper variable outside the function either: only the two items of the array are used.
Asked at ServiceNow · Source
Loading the editor...
- Input
swapPair([ 1, 2 ])Expected[ 2, 1 ] - Returns the same array, now swapped
- No let, const or var inside the function
- swapPair has only one parameter
- No global variable is created
Hidden tests run on Submit