Example 1
ready- Input
x = 123- Expected
321- Why
- the three digits trade places
Turning a number around looks like a string trick until the reversed digits no longer fit inside the integer type.
Given a signed 32-bit integer x, reverse its decimal digits and return the result. A
signed 32-bit integer is an integer in the range -2^31 through 2^31 - 1.
Preserve the sign, and let zeros at the old right edge disappear after reversal.
If the reversed value falls outside that range, return 0. This out-of-range event is
called integer overflow.
A few ground rules:
-2^31 <= x <= 2^31 - 1Hints
The magnitude is the value without its sign. Reverse the magnitude's decimal characters, convert back to a number, then apply the sign and range check.
Remainder by 10 gives the last digit. Integer division by 10 removes it. Append
that digit to the result with result * 10 + digit.
Before result * 10 + digit, compare result with the last safe prefix. Positive
results may end in at most 7; negative results may end in at most 8 in magnitude.
Can you reverse the number with arithmetic alone and constant extra space?
Visible cases
x = 123321x = -123-321x = 12021Interview signal
Separate the sign from the magnitude, reverse the magnitude's characters, and convert the result back to an integer. The conversion naturally drops leading zeros. One final range check handles overflow.
def reverse(x: int) -> int:
sign = -1 if x < 0 else 1
reversed_value = int(str(abs(x))[::-1])
answer = sign * reversed_value
if answer < -(2**31) or answer > 2**31 - 1:
return 0
return answerTime O(d) for d decimal digits. Space O(d) for the string and its reversal.
Arithmetic can move the last digit of the input onto the end of the result. Before
multiplying the result by 10, compare it with the largest prefix the relevant signed
limit can still accept.
def reverse(x: int) -> int:
is_negative = x < 0
remaining = abs(x)
limit = 2**31 if is_negative else 2**31 - 1
reversed_value = 0
while remaining > 0:
digit = remaining % 10
remaining //= 10
if reversed_value > (limit - digit) // 10:
return 0
reversed_value = reversed_value * 10 + digit
return -reversed_value if is_negative else reversed_valueThe negative limit has magnitude 2^31, one larger than the positive limit. Choosing
the limit from the original sign keeps that asymmetry explicit. The guard proves the
next multiplication and addition stay in range before performing them.
Time O(d) because each digit is popped once. Space O(1) because only numeric accumulators are kept.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
321