Today I am going to show how to solve the Leetcode Reverse Integer algorithm problem.
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
}
Top comments (5)
Hi Urfan, I want to suggest another solution:
even shorter:
Cheers.
let reversed = x.toString().split("").reverse().join("");
return parseInt(reversed) * Math.sign(x);
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.
Just a minor improvement to avoid calculating power n times in loop,
All the possible solutions of "Reverse Integer" problem in one video - youtu.be/7PggscnU1Sk
Some comments have been hidden by the post's author - find out more