loading...

Leetcode - Reverse Integer (with JavaScript)

urfan profile image Urfan Guliyev ・1 min read

Today I am going to show how to solve the Leetcode Reverse Integer algorithm problem.

Here is the problem:
Alt Text

1) I declare the two variables revNum and lastDigit, which represent the reverse and the last digit of giving integer x, respectively. Then, I loop through x and build up the reverse integer one digit at a time.

const reverse = function(x){
    let revNum = 0, lastDigit = 0;
}

2) The remainder of a number divided by 10 will give us the last digit.
For example: 123/10 = 12.3 -> the remainder is 3, which is the last digit.

const reverse = function(x){
    let revNum = 0, lastDigit = 0;
    while (x!==0) {
        lastDigit = x % 10; 
    }
}

3) Then, I remove that digit from the end of x by using parseInt() method.
For example: parseInt(12.3) = 12

const reverse = function(x){
    let revNum = 0, lastDigit = 0;
    while (x!==0) {
        lastDigit = x % 10; 
        x = parseInt(x/10);
        revNum = revNum * 10 + lastDigit; // building up the reverse number
   }
}

4) In the problem it was noted that we are dealing with an environment which could only store integers within the 32-bit signed integer range. I therefore check beforehand whether or not appending another digit would cause overflow. If it causes overflow, the loop will break and return 0.

const reverse = function(x){
    let revNum = 0, lastDigit = 0;
    while (x!==0) {
        lastDigit = x % 10; 
        x = parseInt(x/10); 
        revNum = revNum * 10 + lastDigit;
        if (revNum < Math.pow(-2, 31) || revNum > Math.pow(2, 31) - 1) return 0
    }
    return revNum
}

Posted on by:

urfan profile

Urfan Guliyev

@urfan

Love coding, eating and travelling

Discussion

markdown guide
 

Hi Urfan, I want to suggest another solution:

const reverse = n => {
  const str      = "" + Math.abs(n); // convert absolute value to string
  const reversed = str.split("")     // get array of digit characters
                   .reverse()        // reverse it
                   .join("");        // join into string again;
  const num      = +reversed;        // convert integer
  return (n < 0 ? -1 : 1) * num;     // multiple by -1 if needed
}

even shorter:

const reverse = n => (n < 0 ? -1 : 1) * +("" + Math.abs(n)).split``.reverse().join``;

Cheers.