DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on

9 3

Leetcode - Reverse Integer (with JavaScript)

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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
}


Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (5)

Collapse
 
namhle profile image
Nam Hoang Le • Edited

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
}
Enter fullscreen mode Exit fullscreen mode

even shorter:

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

Cheers.

Collapse
 
soma profile image
Amos Gichero

let reversed = x.toString().split("").reverse().join("");
return parseInt(reversed) * Math.sign(x);

Collapse
 
matul3jan profile image
Matul Jain

Your solution does not cover the condition to return 0 if number is out of bound, that's why numeric approach is more feasible here.

Collapse
 
matul3jan profile image
Matul Jain

Just a minor improvement to avoid calculating power n times in loop,

var reverse = function(x) {
    let result = 0;
    const MIN = Math.pow(-2, 31), MAX = Math.pow(2, 31) - 1;
    while (x !== 0) {
        let last = x % 10;      // save last bit
        x  = parseInt(x / 10);  // discard last bit
        result = (result * 10) + last;
        if (result < MIN || result > MAX) return 0;
    }
    return result;
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vilskyviktor profile image
Viktor Vilsky
Comment hidden by post author

Some comments have been hidden by the post's author - find out more

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay