Reverse Integer
Learn an efficient mathematical approach to reverse an integer without converting it to a string, using modulo and integer division.
In depth
Reversing an integer means rearranging its digits in the opposite order. This process is crucial in various algorithms and can be performed efficiently using mathematical operations rather than slower string conversions.
How It Works
The core idea is to extract digits from the original number one by one, starting from the rightmost digit, and then construct a new number using these digits in reverse order. This is achieved using the modulo operator (`%`) and integer division (`//`).
Initialization
We begin with a `rev` variable initialized to `0`. This variable will accumulate the reversed digits.
Extracting Digits
To get the last digit of an integer `x`, we use the modulo operator: `pop = x % 10`. For example, `456 % 10` yields `6`.
Removing Extracted Digits
After extracting a digit, we remove it from the original number using integer division: `x = x // 10`. So, `456 // 10` becomes `45`.
Building the Reversed Number
Each extracted digit `pop` is appended to `rev`. To make space for the new digit, `rev` is first multiplied by `10`, effectively shifting its existing digits to the left. Then, the `pop` digit is added: `rev = rev * 10 + pop`. If `rev` is `0` and `pop` is `6`, `rev` becomes `6`. If `rev` is `6` and `pop` is `5`, `rev` becomes `65`.
Iteration
These steps (extracting, removing, and building) are repeated within a loop until the original number `x` becomes `0`, indicating all digits have been processed.
def reverse_int(x):
rev = 0
while x > 0:
pop = x % 10
x //= 10
rev = rev * 10 + pop
return revKey Takeaways
- Reversing an integer mathematically avoids the overhead of string conversions.
- The modulo operator (`% 10`) isolates the rightmost digit.
- Integer division (`// 10`) removes the rightmost digit.
- Multiplying the reversed number by `10` shifts existing digits left, making room for new ones.
- The process continues until the original number is reduced to zero.
Got a different question? SeaThru generates a fresh video for any topic where systems talk or data structures move.
Ask your own question →