Reverse Integer
Challenge Description
Given an integer, reverse its digits and return the result. For example:
- 1234 becomes 4321
- -5678 becomes -8765
Tips to Solve
- Convert the number to a string using the
toString
method. - Convert the string to an array using the
split
method. - Reverse the array using the
reverse
method. - Convert the array back to a string using the
join
method. - Convert the string back to a number using the
parseInt
method. - Maintain the sign of the original number.
Step-by-Step Solution
Let's break down the solution into easy steps:
-
Convert the Number to a String: Use the
toString
method to convert the number into a string.const str = (1234).toString(); // "1234"
-
Convert the String to an Array: Use the
split
method to convert the string into an array of characters.const strArray = str.split(""); // ["1", "2", "3", "4"]
-
Reverse the Array: Use the
reverse
method to reverse the order of the elements in the array.const reversedArray = strArray.reverse(); // ["4", "3", "2", "1"]
-
Convert the Array Back to a String: Use the
join
method to combine the elements of the array back into a string.const reversedString = reversedArray.join(""); // "4321"
-
Convert the String to a Number: Use the
parseInt
method to convert the string back into a number.const reversedNumber = parseInt(reversedString); // 4321
-
Maintain the Sign: Multiply the reversed number by the sign of the original number to maintain its sign.
const finalNumber = reversedNumber * Math.sign(1234); // 4321
Full Solution Code
Here is the complete solution using the steps above:
const reverseInt = (n) => {
const reversed = n.toString().split("").reverse().join("");
return parseInt(reversed) * Math.sign(n);
};
console.log(reverseInt(1234)); // Output: 4321
console.log(reverseInt(-5678)); // Output: -8765
console.log(reverseInt(0)); // Output: 0