Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
1.1. Swap two numbers without a temporary variable
Easy
Topics
This question is in
1. Types, equality and numbersSwapping two values is a step inside many algorithms: reversing an array, shuffling it, sorting it. The usual way uses a third variable to hold one value for a moment. This problem asks for three ways that need no third variable, and for you to see where each one stops working.
Write three functions in swap.js:
swapBySum(a, b)swaps two integers using only+and-.swapByXor(a, b)swaps two 32-bit integers using only the bitwise XOR operator^.swapItems(list, i, j)swaps two items of an array in place with a destructuring assignment.
Signature
function swapBySum(a, b) // returns [b, a]
function swapByXor(a, b) // returns [b, a]
function swapItems(list, i, j) // returns list itself, changedswapBySumandswapByXorchange their own parametersaandb, then end with a return of the array of the two.swapItemschangeslistand returns the same array, not a copy.
Requirements
swapBySumreturns the two values swapped, for positive and negative integers, zero, equal values and integers up to2 ** 52.swapBySumuses only+and-onaandb: it declares no variable (let,const,var) and builds no array before its return.swapByXorreturns the two values swapped, for any 32-bit integers, negative ones and zero included, and equal values.swapByXoruses only^, with the same rule: no variable and no array before its return.swapItemsswaps the items atiandjin the array passed in and returns that array.swapItemsworks for any order ofiandj, fori === j, and for any kind of item, and leaves every other item and the length alone.
Examples
swapBySum(3, 7); // [7, 3]
swapBySum(-4, 9); // [9, -4]swapByXor(12, 5); // [5, 12]
swapByXor(-1, 77); // [77, -1]const list = ["a", "b", "c"];
swapItems(list, 2, 0); // ["c", "b", "a"]
list; // ["c", "b", "a"]: the same array, changed
swapItems(list, 1, 1); // ["c", "b", "a"]: nothing to swapEnvironment
- Plain JavaScript in a browser page; the tests call the globals
swapBySum,swapByXorandswapItemsfromswap.js. - Two tests read the source of
swapBySumandswapByXor, without comments, up to the lastreturn. Keep the return as the last statement. - Floating-point numbers are not part of the tests for
swapBySum, and numbers outside 32 bits are not part of the tests forswapByXor: both are explained in the solution.
Hints
- After
a = a + b, the variableaholds both numbers at once. How do you get the oldaback out of it? - What is
x ^ x? What isx ^ 0?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…