Date and Time: Sep 3, 2024, 22:21 (EST)
Link: https://leetcode.com/problems/reverse-integer/
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1]
, then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
-2^31 <= x <= 2^31 - 1
-
We use
is_negative
to know ifx < 0
or not.res
to store the reversed x. -
We know
%
can getx
's last digit, and each time we canres * 10
and add the last digit ofx
to updateres
, and updatex //= 10
, so we can shortenx
to get the next digit. -
Lastly, we check if the reversed x
res
is in the range[-2^31, 2^31-1]
, if not, we return0
. (Only check the reversed x) -
Then, we return
res
and negate it depends onis_negative
.
class Solution:
def reverse(self, x: int) -> int:
res = 0
is_negative = False
# Check if x is negative number
if x < 0:
x = -x
is_negative = True
# Reversing
while x > 0:
res = res * 10 + (x % 10)
x //= 10
# Check if the reversed x is within the range
if (is_negative and -res < -2**31) or (not is_negative and res > 2**31-1):
return 0
return -res if is_negative else res
Time Complexity: n
is the length of x
.
Space Complexity: