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 , return 0.
๐ก Intuition
Reversing digits mathematically uses the modular operator to extract the last digit and integer division to remove it: , then . The extracted digit is appended to the reversed number by shifting left: .
๐ง Approach
- Handle the sign: store
is_negative = n < 0and work withabs(n). - While
n > 0, extract the last digit vian % 10and append to result viaresult = result * 10 + digit. - Remove the last digit with
n = n // 10. - After the loop, reapply the sign if needed.
- Check overflow: if the result is outside , return 0.
โก Complexity Analysis
Time
โ the number of iterations equals the number of digits in
Space
โ 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.