Javascript Reversed Integer Problem

Doing the Javascript reversed integer problem is pretty straightforward after doing the reversed string problem.  The only extra steps are to convert the number into a string “.toString()”, then an array “.split(”) and “.reverse()” to reverse it.  Finally, I need to use “.join(”) to convert it from an array back into a string, and “parseInt()” to convert the string back into a number.

However, negative numbers become a problem.  Assume I start with n=-123.  After it is reversed, the negative sign will be at the end of the string (“321-“, for example).  To take that into account, I use “Math.sign()” to store the sign to the variable “sign”.  Math.sign() will return 1 for positive number and -1 for a negative number.

parseInt(“321-“) will return 321.  Then I multiply that number by my “sign” variable -1 to get -321.

function reverseInt(n) {
	const sign = Math.sign(n);
	const revN = n.toString().split("").reverse().join("");
	return parseInt(revN)*sign;

parseInt(revN) * sign //

parseInt(321) *  -1 //

321 * -1 = -321

Leave a Reply

Your email address will not be published. Required fields are marked *