Algorithm LogbookAlgorithm Logbook

Reverse Number

Basic Math

๐Ÿ“‹ Problem Statement

Given an integer, reverse its digits. For example, 1234 becomes 4321, and -1234 becomes -4321. Note: If the reversed number would overflow a 32-bit integer range [โˆ’231,231โˆ’1][-2^{31}, 2^{31}-1], return 0.

๐Ÿ’ก Intuition

Reversing digits mathematically uses the modular operator to extract the last digit and integer division to remove it: last_digit=nโ€Šmodโ€Š10\text{last\_digit} = n \bmod 10, then n=โŒŠn/10โŒ‹n = \lfloor n / 10 \rfloor. The extracted digit is appended to the reversed number by shifting left: result=resultร—10+last_digit\text{result} = \text{result} \times 10 + \text{last\_digit}.

๐Ÿ”ง Approach

  1. Handle the sign: store is_negative = n < 0 and work with abs(n).
  2. While n > 0, extract the last digit via n % 10 and append to result via result = result * 10 + digit.
  3. Remove the last digit with n = n // 10.
  4. After the loop, reapply the sign if needed.
  5. Check overflow: if the result is outside [โˆ’231,231โˆ’1][-2^{31}, 2^{31}-1], return 0.

โšก Complexity Analysis

Time

O(logโก10N)O(\log_{10} N) โ€” the number of iterations equals the number of digits in NN

Space

O(1)O(1) โ€” only a few integer variables

โš ๏ธ Common Mistakes

  • Using Python string conversion (str(n)[::-1]) โ€” correct but doesn't handle the overflow check naturally
  • Not preserving the sign: using abs() but forgetting to reapply negative sign
  • Integer overflow: Python has unlimited integers, so you must manually check the 32-bit bounds

๐ŸŽฏ Final Thoughts

This problem teaches digit-by-digit decomposition using modulo and integer division โ€” a pattern that reappears in Armstrong number checks, palindrome number checks, and digit sum calculations.