Javascript: How to Reverse an Integer

Last updated on June 23, 2022 Napoleon Loading... Post a comment

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);
}

That’s if. Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like