Reverse an integer
You are in a phone screen with Bloomberg and the interviewer asks you to reverse an integer without converting it to a string. This problem, commonly known as Reverse Integer, sounds straightforward but it tests whether you truly understand how digits work at the mathematical level. Reaching for toString() and then reversing the characters is the obvious move, but constant space means you need a different strategy entirely.
TL;DR
Use modulo (% 10) to extract the last digit and integer division (/ 10) to remove it. Accumulate digits into a reversed number by multiplying by 10 and adding each extracted digit. This runs in O(n) time (where n is the digit count) and O(1) space.
Why This Problem Matters
Reversing an integer is one of the cleanest introductions to modular arithmetic in interview prep. The modulo-and-divide pattern shows up in digit counting, number palindrome checking, base conversion, and dozens of other number theory problems. Master this pattern here and those problems become much more approachable.
Understanding the Problem
We need to write a method that:
- Takes a non-negative integer as input
- Returns the integer with its digits in reverse order
- Uses constant space (no string conversion)
reverse(123) -> 321
reverse(12) -> 21
reverse(0) -> 0
reverse(1200) -> 21
Edge Cases
- Zero: Returns 0 (the loop never executes)
- Single digit: Returns the same number (one iteration, same result)
- Trailing zeros: 1200 becomes 21 (leading zeros vanish naturally in integers)
- Already a palindrome: 111111 returns 111111
Solution Approach
The key insight is that you can extract digits from right to left using two operations:
input % 10gives you the last digitinput / 10removes the last digit
To build the reversed number, multiply your accumulator by 10 (shifting all existing digits left) and add the newly extracted digit.
Here is how the algorithm processes 12345:
Loading visualization...
Each step peels off the rightmost digit of the input and appends it to the reversed number. After five iterations, the input reaches 0 and the loop terminates with reversed = 54321.
Now look at what happens with trailing zeros, like 1200:
Loading visualization...
The first two extracted digits are both 0. Multiplying 0 by 10 and adding 0 still gives 0, so the leading zeros vanish naturally. No special handling needed.
And for the simplest case, input 0:
Loading visualization...
The while condition input > 0 is false from the start, so the loop never runs and we return 0 immediately.
Implementation
Prefer a different language? Jump to solutions in other languages.
public class Solution {
public int reverse(int input) {
int reversed = 0;
while (input > 0) {
reversed = (reversed * 10) + (input % 10);
input = input / 10;
}
return reversed;
}
}
Let's walk through the code:
- Initialize the accumulator:
reversedstarts at 0 - Loop while digits remain: The condition
input > 0ensures we stop once all digits have been extracted - Extract and accumulate:
input % 10grabs the last digit, and multiplyingreversedby 10 shifts its digits left before adding the new one - Shrink the input:
input / 10drops the last digit via integer division (truncating the decimal)
Complexity Analysis
Time: O(n) where n is the number of digits in the input. Each loop iteration does two constant-time arithmetic operations (modulo and division), and the loop runs exactly n times.
Space: O(1). We use two integer variables regardless of the input size. No arrays, no strings, no additional data structures.
Why Not Convert to a String?
The string approach looks like this:
// Works, but violates the constant-space constraint
return Integer.parseInt(new StringBuilder(String.valueOf(input)).reverse().toString());
This creates a String, a StringBuilder, and another String for the reversed result. That is O(n) space, and it sidesteps the mathematical reasoning that interviewers want to see.
Common Pitfalls
-
Using string conversion: The problem explicitly asks for constant space. Converting to a string uses O(n) space and misses the point of the exercise.
-
Forgetting integer division behavior: In Java and most languages, dividing two integers truncates toward zero.
12345 / 10gives1234, not1234.5. This truncation is exactly what we want, but make sure you understand why. -
Off-by-one with the loop condition: Using
input >= 0instead ofinput > 0creates an infinite loop because0 / 10is still0. The loop must terminate when the input reaches zero. -
Not considering trailing zeros: Some candidates add special logic for trailing zeros (like 1200). It is unnecessary because the mathematical approach handles them automatically.
Interview Tips
When presenting this solution:
- Clarify the constraints up front: non-negative integers, constant space
- Explain the modulo-and-divide pattern by name. Interviewers like hearing you recognize it.
- Walk through a small example on paper: show how
12345 % 10 = 5, then12345 / 10 = 1234 - Mention that trailing zeros are handled automatically, without special cases
- If asked about negative numbers or overflow, explain how you would extend the solution (store sign, check bounds before accumulating)
Key Takeaways
- The modulo operator (
% 10) extracts the last digit of a number, and integer division (/ 10) removes it. Together they let you peel digits from right to left. - Building the reversed number is a matter of shifting the accumulator left (multiply by 10) and adding each new digit.
- Trailing zeros in the original number become leading zeros in the result, which integers discard automatically.
- This problem introduces the modulo-and-divide pattern, which is foundational for digit counting, palindrome numbers, base conversion, and similar number theory problems.
- The O(1) space requirement rules out string conversion. Always confirm space constraints before choosing your approach.
Practice and Related Problems
Once you are comfortable with integer reversal, try these progressions:
- Palindrome number tester (reverse half and compare)
- Count digits in a number (same loop structure)
- Convert between number bases (same modulo-and-divide pattern)
This problem and hundreds of others are available on Firecode, where consistent daily practice helps you build the pattern recognition that top tech companies look for. Whether you are warming up for phone screens or preparing for on-site interviews, starting with fundamentals like this sets you up well.
Solutions in Other Languages
Python
class Solution:
def reverse(self, input_int: int) -> int:
reversed_out = 0
while input_int > 0:
reversed_out = (reversed_out * 10) + (input_int % 10)
input_int = input_int // 10
return reversed_out
JavaScript
class Solution {
reverse(input) {
let reversed = 0;
while (input > 0) {
reversed = (reversed * 10) + (input % 10);
input = Math.floor(input / 10);
}
return reversed;
}
}
TypeScript
class Solution {
reverse(input: number): number {
let reversed = 0;
while (input > 0) {
reversed = (reversed * 10) + (input % 10);
input = Math.floor(input / 10);
}
return reversed;
}
}
C++
class Solution {
public:
int reverse(int input) {
int reversed = 0;
while (input > 0) {
reversed = (reversed * 10) + (input % 10);
input = input / 10;
}
return reversed;
}
};
Go
package solution
func (s *Solution) Reverse(input int) int {
reversed := 0
for input > 0 {
reversed = (reversed * 10) + (input % 10)
input = input / 10
}
return reversed
}
Scala
class Solution {
def reverse(input: Int): Int = {
var reversed = 0
var dividend = input
while (dividend > 0) {
reversed = (reversed * 10) + (dividend % 10)
dividend = dividend / 10
}
reversed
}
}
Kotlin
class Solution {
fun reverse(input: Int): Int {
var reversed = 0
var num = input
while (num > 0) {
reversed = (reversed * 10) + (num % 10)
num = num / 10
}
return reversed
}
}
Swift
class Solution {
func reverse(_ input: Int) -> Int {
var reversed = 0
var num = input
while num > 0 {
reversed = (reversed * 10) + (num % 10)
num = num / 10
}
return reversed
}
}
Rust
impl Solution {
pub fn reverse(&self, mut input: i32) -> i32 {
let mut reversed = 0;
while input > 0 {
reversed = (reversed * 10) + (input % 10);
input = input / 10;
}
reversed
}
}
C#
public class Solution {
public int reverse(int input) {
int reversed = 0;
while (input > 0) {
reversed = (reversed * 10) + (input % 10);
input = input / 10;
}
return reversed;
}
}
Dart
class Solution {
int reverse(int input) {
int reversed = 0;
int num = input;
while (num > 0) {
reversed = (reversed * 10) + (num % 10);
num = num ~/ 10;
}
return reversed;
}
}
PHP
class Solution {
public function reverse(int $input): int {
$reversed = 0;
while ($input > 0) {
$reversed = ($reversed * 10) + ($input % 10);
$input = intdiv($input, 10);
}
return $reversed;
}
}
Ruby
class Solution
def reverse(input)
reversed = 0
while input > 0
reversed = (reversed * 10) + (input % 10)
input = input / 10
end
reversed
end
end