EXERCISE · AlgoCasts
Reverse integer
Given an integer, return an integer that is the reverse ordering of numbers.
Directions
Directions
Given an integer, return an integer that is the reverse ordering of numbers.
Examples#
JS
reverseInt(15) === 51reverseInt(981) === 189reverseInt(500) === 5reverseInt(-15) === -51reverseInt(-90) === -9Try it first#
Copy the stub, make the 4 tests pass on your machine, then open the solution. The reveal is remembered per page in this browser.
JSexercises/reverseint/index.js
function reverseInt(n) {} module.exports = reverseInt;Solution#
JScompleted_exercises/reverseint/index.js
// Hint Math.sign or -1 is a negative greater than 0 or less than 0 function reverseInt(n) { const reversed = n .toString() .split('') .reverse() .join(''); return parseInt(reversed) * Math.sign(n);} module.exports = reverseInt;const reverseInt = require('./index'); test('ReverseInt function exists', () => { expect(reverseInt).toBeDefined();}); test('ReverseInt handles 0 as an input', () => { expect(reverseInt(0)).toEqual(0);}); test('ReverseInt flips a positive number', () => { expect(reverseInt(5)).toEqual(5); expect(reverseInt(15)).toEqual(51); expect(reverseInt(90)).toEqual(9); expect(reverseInt(2359)).toEqual(9532);}); test('ReverseInt flips a negative number', () => { expect(reverseInt(-5)).toEqual(-5); expect(reverseInt(-15)).toEqual(-51); expect(reverseInt(-90)).toEqual(-9); expect(reverseInt(-2359)).toEqual(-9532);}); Verbatim from the repo at 30cf7634. Alternate tabs are the commented-out solutions with the leading // removed and nothing else changed. Run the tests locally with npx jest reverseint inside the fork.
See also