On the other hand, `parseInt()` is a method used to parse a string and return an integer:
We will use these methods in our approach to reverse a number.
- Convert the number into a string using the `toString()` method.
- Split the string into an array of characters using the `split(”)` method.
- Reverse the array using the `reverse()` method.
- Join the reversed array back into a string using the `join(”)` method.
- Convert the string back into an integer using the `parseInt()` method.
Here is an implementation of these steps:
We can make this code more efficient by chaining all the operations in one line:
Handling Negative Numbers
The above code works well for positive numbers. However, for negative numbers, it will return a positive reversed number due to the `parseInt()` method. Here is how to handle negative numbers:
In this code, we use a ternary operator to check if the original number was negative. If it was, we return the reversed number as a negative number. Otherwise, we return it as a positive number.