Reverse Integer – Solution & Complexity
Solution Walkthrough
Step 1: Separate sign from magnitude
- Record whether
xis negative, then work with the absolute value so digit extraction is uniform. - Reversing the digits of the magnitude and reapplying the sign at the end keeps the logic simple.
- Trailing zeros vanish automatically because a leading zero in the reversed number carries no value.
- Record whether
Step 2: Peel digits off with mod and divide
- Repeatedly take
n % 10to read the last digit andn // 10to drop it. - Build the reversed value as
rev = rev * 10 + digit. - Stop when
nreaches zero.
- Repeatedly take
Step 3: Guard the 32-bit range
- After reapplying the sign, check whether the result falls outside
[-2147483648, 2147483647]. - If it does, return
0. - With only 32-bit arithmetic you would instead check, before each
rev * 10 + digit, whetherrevalready exceeds2147483647 / 10.
- After reapplying the sign, check whether the result falls outside
Step 4: Reference solution
- Extract digits from the magnitude, reverse, reapply the sign, and clamp to zero on overflow.
- Time is
O(log10(x))(the digit count); space isO(1).
Step 5: Common mistakes
- Forgetting the overflow check and returning a value outside the 32-bit range.
- Mishandling negative mod/division semantics in languages where
%keeps the dividend's sign. - Dropping the sign, so
-123reverses to321instead of-321.