Specifically, the challenge is to return the inputted 32-bit integer, with its digits reversed. We are to assume the environment does not allow you to store 64-bit integers (signed or unsigned). Signed or unsigned refers to designating whether the integer is positive or negative. This parameter results in the constraint that if reversing x causes the value to go outside the signed 32-bit integer range, then return 0. This range is [-2³¹, 2³¹ - 1].
Let’s start with a big picture plan of how we are going to approach this problem. First, we can reverse the given integer, and then identify if the integer falls within the allowed range of values.
Now, our use of parseInt() has resulted in an issue we’ll have to address. If the input integer was a negative number, the reverseDigits variable wouldn’t know the difference because parseInt() has removed any negative signs. Fortunately, using an if statement, we can solve that signage and the range issues all at once.
The first condition that we’ll pass into the if statement will find positive values, or zero, that are within the allowed range. We’ll say that if the input is greater than or equal to zero, and the reverseDigits variable is less than 2³², which is 2147483648, then return reverseDigits.
To account for the negative numbers that pass inside the allowed range, we’ll use an else if statement. The condition passed into this statement will be if the input is less than zero, and reverseDigits times -1 is less than 2³², return reverseDigits times -1. This will return any integers to a negative value that were originally negative that fit within the allowed range.
Finally, to account for all integers whose value when its digits are reversed, are no longer within the valid range, we can conclude with an else block that will simply return zero. Here is the function in its completion.