Skip to content

Instantly share code, notes, and snippets.

@GreggSetzer
Last active February 3, 2018 20:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GreggSetzer/b798512725db26dc7d6cbdb566cc2347 to your computer and use it in GitHub Desktop.
Save GreggSetzer/b798512725db26dc7d6cbdb566cc2347 to your computer and use it in GitHub Desktop.
Javascript Interview Question: Reverse a Number
/*
Reverse a number.
*/
function reverseInt(num) {
//Convert the num to a string, reverse the chars.
const reversedStr = num.toString().split('').reverse().join('');
//Convert back to an int, restore the sign (+ or -), return result as number.
return parseInt(reversedStr) * Math.sign(num);
}
//Jest
test('It should reverse 123 to 321.', () => {
expect(reverseInt(123)).toEqual(321);
});
test('It should reverse 120 to 21.', () => {
expect(reverseInt(120)).toEqual(21);
});
test('It should reverse -150 to -51.', () => {
expect(reverseInt(-150)).toEqual(-51);
});
//Try it.
console.log(reverseInt(25));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment