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:
- Convert the integer to a string
- Reverse that string
- 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:
- Vanilla Javascript: Detect a click outside an HTML element
- VS Code & Javascript/TypeScript: Place Curly Braces on New Line
- Javascript: Looping through Keys/Values of an Object
- Javascript: Set HTML lang attribute programmatically
- TypeScript: Using Variables to Set Object Keys
- Node.js: Ways to Delete All Files in a Folder
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
0 Comments