# Javascript: How to Reverse an Integer

In Javascript, you can reverse a given integer (e.g. turn 123 to 321, -456 to -654, 1200 to 21) by performing the following steps:

1. Convert the integer to a string
2. Reverse that string
3. Turn the reversed string to an integer. If the input is a negative number, we must multiply the result with -1 (because the minus sign will be lost even if the input is a negative integer)

These words might sound boring and unclear enough. The program below will help you understand the solution better:

``````function reverseInt(input){
// turn the input to a string
var str = input.toString();

// reverse the string
var reversedStr = str.split('').reverse().join('');

// turn the reversed string to an integer
var reversedInt = parseInt(reversedStr);

// deal with the negative sign if it exists
if(reversedStr.search('-') !== -1){
reversedInt = reversedInt * -1;
}

// return the result
return reversedInt;
}

// Test it
console.log(reverseInt(123));
console.log(reverseInt(-12345));
console.log(reverseInt(33900));``````

Output:

``````321
-54321
933``````

We can condense the reverseInt() function above to make it more succinct like this:

``````function reverseInt(input) {
return parseInt(input.toString().split('').reverse().join(''))
* Math.sign(input);
}``````