How to reverse a number as an integer and not as a string?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Reversing an integer without converting it to a string is a small arithmetic exercise built on modulus and integer division. The core idea is to pull digits from the end of the number one at a time and push them into a new result from left to right.
The Core Arithmetic Idea
For a positive integer n:
- '
n % 10gives the last digit' - '
n // 10removes the last digit' - '
result * 10 + digitappends the extracted digit to the reversed number'
This is enough to rebuild the number in reverse order.
Python Example
Here is a straightforward implementation in Python.
This keeps the work numeric the whole time. No string conversion is needed.
Walk Through The Steps
Take 1234 as an example.
- start with
result = 0 - extract
4, soresult = 0 * 10 + 4 = 4 - extract
3, soresult = 4 * 10 + 3 = 43 - extract
2, soresult = 43 * 10 + 2 = 432 - extract
1, soresult = 432 * 10 + 1 = 4321
The original number shrinks until it reaches 0, while the reversed result grows in the opposite order.
Java Example With Overflow Check
In languages with fixed integer ranges, you also need to consider overflow.
Java's % and / operators also work for negative numbers, so you can implement the reversal without converting to positive first if you prefer.
What Happens With Trailing Zeros
Trailing zeros disappear naturally because integers do not store them.
This returns 21, not 0021, because 0021 and 21 are the same integer value.
Complexity
The algorithm runs in O(d) time, where d is the number of digits, and uses O(1) extra space. That is optimal for this style of reversal.
Why Interview Questions Use This Problem
This problem checks whether you understand base-10 arithmetic, loops, integer operators, and overflow handling. It is simple enough to explain on a whiteboard, but it still reveals whether someone can reason through state changes carefully.
Common Pitfalls
A common mistake is forgetting to preserve the sign for negative numbers. If you use abs(n) during the loop, remember to restore the sign at the end.
Another mistake is ignoring overflow in languages with fixed-width integers such as Java or C. Reversing a large number can exceed the target type range.
It is also easy to expect leading zeros in the output. Reversing 100 as an integer gives 1, because integer values do not retain formatting zeros.
Summary
- Use modulus to extract the last digit and integer division to remove it.
- Build the reversed number with
result = result * 10 + digit. - The algorithm works in linear time relative to the number of digits.
- Handle signs and overflow explicitly when the language requires it.
- Integer reversal does not preserve leading or trailing formatting zeros.

