REVERSE INTEGER LeetCode Problem07 Solution using Python language
______________________________________________________________________________________________________________________________________________________
Description :
Initialization: r, temp, and s are initialized to 0, the original input x, and the reversed number, respectively.
Handling Negative Input: If x is negative (x less than 0), the code temporarily changes x to its absolute value (-x). This is done to simplify the process of reversing the digits, as the logic remains the same regardless of the sign.
Digit Reversal Loop: The while loop iterates through the digits of x. In each iteration, it calculates the remainder r when dividing x by 10, updates the reversed number s by multiplying it by 10 and adding the remainder, and then updates x by integer division (x // 10), effectively removing the last digit.
Overflow Check: After the loop, it checks if the reversed number s exceeds the 32-bit signed integer range (s greater than pow(2, 31)). If it does, the function returns 0 to avoid overflow issues.
Restoring Original Sign: If the reversed number is within the valid range, it checks the original sign (temp). If temp is non-negative (temp greater than equal to 0), it returns the reversed number s. Otherwise, it returns the negation of s to restore the original sign.