Leetcode Problem 7: Reverse Integer

3/7/2024

Summary

A solution to LeetCode's Reverse Integer problem using string conversion and array manipulation to efficiently reverse digits while handling negative numbers and 32-bit integer constraints.

Introduction

Today, I solved my first medium-difficulty problem on LeetCode — The Reverse Integer. Here, I want to explain the problem and my approach to solving it. I’d like to mention that this was just my way of solving the problem and that it certainly isn’t the perfect solution.

The Problem explained

An integer x, such as x=123 or x=-122, is given as input.
The output should be the given input in reverse order. If the output exceeds the signed 32-bit range [-2³¹ to (2³¹)-1], the output should be 0.
Examples:
Input: x=123 — Output: x=321
Input: -123 — Output: -321
Input: x=120 — Output: x=21

The solution

Basic idea

The first idea that came to mind was to convert the input integer into an array. This would allow me to extract the sign “-” if the number is negative, store it in a separate variable, and remove it from the array. This way, I would only have to work with an array of integers.
Afterward, I would need to reverse the array and convert it back into an integer.
Finally, I would need to check if the integer falls within the range of 32 bits. If the input was negative, I must convert the result back to a negative integer.

1) Extract sign of the input

So, my initial approach to solving this problem involves converting the input into an array of strings and checking whether the number is negative.
The state of the sign should be stored as a boolean variable named “positive”. When implemented in code, it looks like this:
var reverse = functions(x){
let xArray = x.toString().split("");
let positive = true;

if(xArray[0] === "-"){
positive = false;
xArray.shift();
}
}

2) Reverse array and convert it to integer

After extracting the minus sign, if present, we proceed to the next step. Now, we need to reverse the array and convert it back into an integer. This is accomplished by reversing the array using the built-in `.reverse()` function in JavaScript. Afterward, we iterate over the array, which still contains the values as strings, to convert them into an array of integers. Once we complete this step, we need to convert the array of integers back into a single integer and store this integer in a variable.
//...
xArray.reverse()
let reversedXArray = []

for(let i=0; i<xArray.length; i++){
reversedXArray.push(parseInt(xArray[i], 10))
}

let number = parseInt(reversedXArray.join(''));
//...

3) Convert number to negative if input was negative

In the third step, we revisit the variable where we earlier stored whether the input was positive or negative. If the number was negative, we need to multiply the final integer by -1 to obtain the negative number.
//...
if (!positive) {
number *= -1;
}
//...

4) Check for int in range of 32 bit

One last step remains. If you carefully read the problem description, you’ll notice that the final output should be 0 if the integer doesn’t fit into the 32-bit range. To implement this in code, I wrote a helper function that returns true if the number fits into the range of 32 bits, and false if it doesn’t. At the end of the function, we check if it fits into the range. If not, we return 0; otherwise, we return the number.
function isInteger32Bit(num) {
return num >= -(2**31) && num <= (2**31 - 1);
}

//...

if(isInteger32Bit(number)===false){
return 0
}

return number
};

5) Final code

Heres the final code:
function isInteger32Bit(num) {
return num >= -(2**31) && num <= (2**31 - 1);
}
var reverse = function(x) {

let xArray = x.toString().split("");
let positive = true;

if(xArray[0] === "-"){
positive = false;
xArray.shift();
}

xArray.reverse()
let reversedXArray = []

for(let i=0; i<xArray.length; i++){
reversedXArray.push(parseInt(xArray[i], 10))
}

let number = parseInt(reversedXArray.join(''));

if (!positive) {
number *= -1;
}

if(isInteger32Bit(number)===false){
return 0
}

return number
};
Finally, we can submit the solution and check if the code is correct.
We have successfully completed the problem within a runtime of 76 ms, which is faster than 39.46% of the JavaScript submissions on LeetCode, with a memory usage of 52.5 MB, which is less than 62.26% of the JavaScript submissions.
Of course, these stats aren’t perfect, but I count myself still a beginner at LeetCode. If you have found a better solution, feel free to contact me and show it to me.

Final words

I hope you enjoyed reading this article.
If you have any questions or remarks feel free to contact me.
Your Mario 💚