JS Algorithm – Reverse Int
Chichén Itzá, Mérida, Mexico by https://unsplash.com/@mrvphotography
Given an integer, return an integer that is the reverse ordering of numbers.
Examples:
reverseInt(15) === 51
reverseInt(981) === 189
reverseInt(500) === 5
reverseInt(-15) === -51
reverseInt(-90) === -9
Solution:
function reverseInt(n) {
// Converting the integer number to string.
// then convert to an array and reverse that array
// then with join we are back the array to string
let reversedString = n.toString().split('').reverse().join('');
// converting the string to integer
// Math.sign => It returns 1 if the argument passed is a positive.
// It returns -1 if the argument passed is a negative.
return parseInt(reversedString) * Math.sign(n);
}
reverseInt(500);
Result:
By Cristina Rojas.