Reverse the Number

Setu Potnis
1 min readMay 18, 2020

--

Day 28

Hey guys, I hope everyone has had an amazing Sunday so far, for today’s algorithm problem, I’ll be reversing an integer. Yeah, it’s pretty straightforward, but just to make sure, I’ll give you an example:

let num1 = 324;
//function returns
423
let num2 = -762;
//function returns
-267

Since JavaScript has so many built-in functions, I started off by turning the integer to a string and used string methods to flip the integer around. Here’s what the code looks like:

var reverse = function(x) {
let r = parseInt(x.toString().split('').reverse().join(''))
if (r < -2147483648 || r > 2147483647) return 0
return (x < 0) ? -r : r
};

I basically check if the number is a 32-bit signed integer on the second line, and once I have done that, I can return the reversed number pretty easily.

Let me know if you liked the solution or have any questions. Hit the clap button if you learned something cool, thanks!

--

--

Setu Potnis

An IBM Software Engineer passionate about crafting exceptional digital experiences for users