7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For this problem, assume that your function returns 0 when the reversed integer overflows.
Input: x = 123
Input: x = -123
Input: x = 120
Input: x = 0
-2^31 <= x <= 2^31 - 1
We need to keep in mind that the given system can handle only 32-bit signed integers, Hence we should be careful while reversing the integer.
As the first step, we need to check if the given number is positive or negative. An appropriate flag needs to be set based on the sign of the given integer.
Next, we need to run the loop until we have digits in our number.
To reverse the integer, we need to get the last digits and put them in the front. To get the last digits, we would take the modulus of the given number by 10. The obtained number is then multiplied by 10. The previous number is divided by 10 so that we can omit the last digit as we have already processed it.
Each time the number is multiplied by 10, we need to ensure that the number is well within the constraint given. Based on the sign flag, we can convert the obtained answer to a negative number if required.
def reverse(self, x: int) -> int:
negative = False
output = 0
if x < 0:
negative = True
x *= -1
output = output*10 + x%10
x = x//10
if((negative == False and output > pow(2, 31)-1 )or(negative and output > pow(2, 31))) :
output *= -1
We will be running the loop until we traverse through all the digits in the given number, hence the time complexity is the number of digits.
We are not making use of any data structure to store intermediate results. Therefore space complexity is O(1).
I would love to hear your feedback about my posts. Do let me know if you have any comments or feedback.