Problem overview
The function reverse gets a whole number x that fits in 32 bits, from -2,147,483,648 to 2,147,483,647. It returns x with its digits in reverse order. A minus sign stays in front, and zeros that end up at the start of the result are dropped. If the reversed number is outside the 32-bit range, the function returns 0.
For 5600 the reversed digits read 0065, so the answer is 65. For -2408 the answer is -8042. For 1000000009 the reversed number would be 9,000,000,001, which is too large, so the answer is 0. The statement asks for O(log |x|) time and O(1) extra space, without a 64-bit integer type.
Approach: peel digits off the right, push them onto the result
The remainder of a division by 10 is the last digit, and dividing by 10 drops it. To build the reversed number, take digits from the right one at a time and append each to the result with result * 10 + digit. For 5600 that gives results 0, 0, 6 and 65, so the leading zeros of the reversed number vanish without any special code.
The 32-bit rule needs an explicit check. Python integers have no fixed size, so 9000000001 is a perfectly good int and nothing would stop it. The function has to compare the result with the limit itself, before adding each digit. If the next value would exceed the limit, it returns 0 at once.
Negative numbers need a small detour. In Python, % and // round toward negative infinity, so -2408 % 10 is 2, and -2408 // 10 is -241. These are not the last digit and the digit-dropped number you want. So the function sets the sign aside, works on abs(x), and puts the sign back at the end.
Because the number has at most 10 digits, the loop runs at most 10 times. In general, the number of digits is about the base-10 logarithm of |x|, which gives the O(log |x|) time.
Step by step
- Record the sign.
signis -1 whenxis negative and 1 otherwise, using a conditional expression:a if condition else b. - Make
xpositive withabs. The digits of -2408 and 2408 are the same. - Set
limit. It is2**31 - 1for a positive answer and2**31for a negative one, because the 32-bit range holds one more negative number than positive ones.**raises to a power. - Start
resultat 0. It collects the digits. - Loop while
x > 0. Each pass removes one digit, so it runs once per digit. - Take the last digit with
x % 10. In-2408the digits come out as 8, 0, 4, 2. - Drop it from
xwithx //= 10. Floor division discards the remainder:2408 // 10is240. - Check before adding. If
result * 10 + digitis greater thanlimit, return 0. This is the key step. For1000000009,resultreaches 900,000,000 before the last digit, and 9,000,000,001 is above the limit. - Add the digit:
result = result * 10 + digit. - Return
sign * resultto put the sign back.
The solution in Python
class Solution:
def reverse(self, x: int) -> int:
sign = -1 if x < 0 else 1
x = abs(x)
limit = 2**31 - 1 if sign == 1 else 2**31
result = 0
while x > 0:
digit = x % 10
x //= 10
if result * 10 + digit > limit:
return 0
result = result * 10 + digit
return sign * result
Python details:
%and//floor toward negative infinity, which is why the code works on a non-negativex. For a positivexthey give the last digit and the number without it, as expected.- Python integers grow as needed and never wrap, so the 32-bit limit must be enforced by the comparison. A shortcut such as
int(str(x)[::-1])returns9000000001for1000000009, not 0, and it does not handle the minus sign. - The check runs on the value about to be stored, so an out-of-range answer is never built. The intermediate values are prefixes of the final reversed number and are never larger than it, so the first time one exceeds the limit, the whole answer would too.
- The parameter
xis reassigned inside the function. This is fine, because integers are immutable and the caller's variable is untouched.
Complexity
The loop runs once per digit, at most 10 times for a 32-bit input, which is O(log |x|). The function stores a few integers, so the extra space is O(1).
Edge cases and common mistakes
- Trailing zeros.
5600gives65, and120gives21. No code is needed to remove the zeros. - Zero.
0gives0, since the loop never runs. - The ends of the range.
2147483647and-2147483648both reverse to numbers beyond 32 bits, so both give0. - Right below the limit.
1463847412reverses to 2147483641, which fits, so the answer is2147483641, and-1463847412gives-2147483641. - Using
%on a negative number.-2408 % 10is 2, not -8. Take the absolute value first. - Checking the limit after the loop. That works in Python for a small number, but the lesson's check, done before adding each digit, shows the habit that is needed in languages where a number can overflow.
Testing
| x | result |
|---|---|
5600 | 65 |
-2408 | -8042 |
1000000009 | 0 |
-10 | -1 |
1463847412 | 2147483641 |
2147483647 | 0 |
