- Published on
Reversing integers in JavaScript
- Authors
- Name
- Inés San Luís
Introduction
Reversing an integer in JavaScript is a common problem that tests a programmer's ability to manipulate numbers and strings. The challenge is to take an integer and return a new integer that represents the original number's digits in reverse order. This problem becomes more interesting when it involves both positive and negative numbers. For example, reversing 15
should return 51
, while reversing -15
should yield -51
. Handling cases like 500
, where the reversed integer should not have leading zeros, adds another layer to the challenge.
Solution
Here's an efficient way to reverse an integer:
function reverseInt(n) {
const reversed = n
.toString()
.split('')
.reverse()
.join('');
return parseInt(reversed) * Math.sign(n);
}
Breaking it down
Converting the integer to a string: First, the integer
n
is converted into a string using thetoString()
method. This is necessary because thesplit
method, which is used next, works on strings, not numbers.Reversing the string: The string is then split into an array of characters, reversed, and joined back into a string. These operations are chained together for efficiency.
Converting back to an integer: The
parseInt()
function is used to convert the reversed string back into an integer.Adjusting for sign: Finally, the result is multiplied by the sign of the original number using
Math.sign(n)
. This ensures that the reversed integer retains the original number's sign, handling both positive and negative integers correctly.
Conclusion
The ability to reverse an integer in JavaScript is a useful skill that combines string manipulation and number handling. The solution provided is both succinct and versatile, effectively dealing with various edge cases such as negative numbers and numbers with trailing zeros. Understanding such problems and their solutions enhances one's capability to tackle a wide range of algorithmic challenges in JavaScript.