Solution: Reverse Integer
Let’s solve the Reverse Integer problem using the Math and Geometry pattern.
Statement
Given a 32-bit signed integer num
, reverse its digits and return the result. If the reversed number exceeds the 32-bit signed integer range
Assume the environment does not support storing 64-bit integers (signed or unsigned).
Constraints:
num
Solution
The solution reverses the digits of num
while ensuring that the result stays within the bounds of a 32-bit signed integer. If the input number is negative, it converts it to its absolute value to simplify processing. The main logic involves repeatedly extracting the last digit of nums
, reducing num
by removing this digit, and appending the digit to the reversed result.
Before appending each digit, the solution checks if the operation would cause the result to exceed the 32-bit signed integer limit. If an overflow is detected, the function returns num
is fully processed (reduced to
The detailed steps of the implementation of the solution are as follows:
Initialize the below variables:
Initialize
INT_MAX
with the maximum value of a 32-bit signed integer.Initialize
result = 0
to store the reversed number.Determine if the number is negative:
is_negative = num < 0
.
If
num
is negative, convert it to its absolute value:num = -num
.Iterate through the digits of
num
whilenum != 0
:Extract the last digit:
digit = num % 10
.Remove the last digit from
num
:num //= 10
.
Before updating the
result
, verify that appending the newdigit
will not cause an overflow:If
result > (INT_MAX - digit) // 10
, return(overflow detected).
Update
result = result * 10 + digit
to append the extracteddigit
to the reversed number.If the original number was negative, return
-result
. Otherwise, returnresult
.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.