Last active
February 3, 2018 20:35
-
-
Save GreggSetzer/b798512725db26dc7d6cbdb566cc2347 to your computer and use it in GitHub Desktop.
Javascript Interview Question: Reverse a Number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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