Reverse Integer Algorithm

Sunday is for coding: today I was working on a reverse integer algorithm!

Leetcode marked it as an easy one, however, it took me some time to get it. There are tons of ways to solve this problem, and this one might be a little clumsy so feel free to refactor it! Also, one of my goals was to practice the Math and Number methods that I haven’t implemented for a while.

So, our task is:

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range, then return 0.

Here is a step-by-step solution:

function reverseInt(x) {   // step 1: Make the number positive (Math.abs) and turn it into a string    let string = Math.abs(x).toString();
let arr = [];
//step 2: Push each string (aKa digit) in the reversed order into an empty array for(let i = string.length - 1; i >= 0; i--) {
arr.push(string[i])
}
// step 3: Turn the reversed string into a number let result = Number(arr.join('')); // step 4: If reversing causes the value to go outside the signed 32-bit integer range, return 0 if (result > 2 ** 31 - 1) {
return 0;
}
// step 5: if x is negative, turn the final number negative if (x < 0) {
let result *= -1;
} return result;
};

Hope this quick walk-through was helpful! For more options, please have a look at the Leetcode discussion board.

Source:

  1. Leetcode

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store