
Sponsored
This method involves extracting digits one at a time from the integer using modulus and division operations. By repeatedly taking the last digit of the number, you can construct the reversed integer. However, special care must be taken to handle the overflow condition, as reversing an integer can potentially produce a value beyond the 32-bit signed integer limit.
Time Complexity: O(log10(x)) because we are processing each digit once.
Space Complexity: O(1) since we are using constant extra space.
1def reverse(x):
2 result = 0
3 while x != 0:
4 pop = x % 10
5 if x < 0 and pop > 0:
6 pop -= 10
7 x = (x - pop) // 10
8 if result > 214748364 or (result == 214748364 and pop > 7): return 0
9 if result < -214748365 or (result == -214748365 and pop < -8): return 0
10 result = result * 10 + pop
11 return result
12
13x = -123
14print(reverse(x))In Python, integer overflow isn't a concern like in other languages, but here a similar approach to digit extraction and accumulation is used, with overflow logic adapted from a 32-bit perspective.
In this approach, the integer is first converted to a string representation, reversed as a string, and then converted back to an integer. This method mitigates overflow issues by checking the integer post-conversion if it falls within the valid range.
Time Complexity: O(n) where n is the number of digits in x.
Space Complexity: O(n) due to the use of the string to store digits temporarily.
1def reverse(x):
2 sign = -
This Python solution converts the integer x to a string, reverses it, and then converts it back to an integer. The sign is preserved and checked for overflow before returning the result.