Reverse an integer

AS
Ackshaey Singh
Difficulty Medium
Time Complexity
O(n)
Space Complexity
O(1)
Number Trick
Firecode Bloomberg

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

  1. Zero: Returns 0 (the loop never executes)
  2. Single digit: Returns the same number (one iteration, same result)
  3. Trailing zeros: 1200 becomes 21 (leading zeros vanish naturally in integers)
  4. 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 % 10 gives you the last digit
  • input / 10 removes 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:

  1. Initialize the accumulator: reversed starts at 0
  2. Loop while digits remain: The condition input > 0 ensures we stop once all digits have been extracted
  3. Extract and accumulate: input % 10 grabs the last digit, and multiplying reversed by 10 shifts its digits left before adding the new one
  4. Shrink the input: input / 10 drops 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

  1. 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.

  2. Forgetting integer division behavior: In Java and most languages, dividing two integers truncates toward zero. 12345 / 10 gives 1234, not 1234.5. This truncation is exactly what we want, but make sure you understand why.

  3. Off-by-one with the loop condition: Using input >= 0 instead of input > 0 creates an infinite loop because 0 / 10 is still 0. The loop must terminate when the input reaches zero.

  4. 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, then 12345 / 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

Frequently Asked Questions

How do you reverse an integer without converting it to a string?
Use the modulo operator (%) to extract the last digit and integer division (/) to remove it. Build the reversed number by multiplying the accumulator by 10 and adding each extracted digit. This runs in O(n) time where n is the number of digits, using O(1) space.
What is the time complexity of reversing an integer?
The time complexity is O(n) where n is the number of digits in the integer. Each iteration of the loop processes one digit using modulo and division, both O(1) operations. The loop runs exactly n times, once per digit.
What is the space complexity of the mathematical integer reversal approach?
The space complexity is O(1) because the algorithm uses only a fixed number of variables (the reversed accumulator and the input) regardless of how many digits the number has. No arrays, strings, or additional data structures are needed.
How does the modulo operator help reverse an integer?
The expression input % 10 extracts the last digit of the number. For example, 12345 % 10 gives 5. Combined with integer division (input / 10, which removes the last digit), you can peel off digits one at a time from right to left and reassemble them in reverse order.
What happens when reversing an integer with trailing zeros?
Trailing zeros in the original number become leading zeros in the reversed result, which naturally disappear in integer representation. For example, reversing 1200 yields 21, not 0021. The algorithm handles this correctly without any special logic.
Can you reverse a negative integer with this approach?
The approach shown here handles non-negative integers (0 to Integer.MAX_VALUE). For negative numbers, you would store the sign, reverse the absolute value, and reapply the sign. The core modulo-and-divide logic remains the same.
What is the difference between reversing an integer and reversing a string?
Reversing a string typically uses character array indexing or two pointers and requires O(n) space for the reversed copy. Reversing an integer uses modular arithmetic and integer division, achieving O(1) space. The mathematical approach avoids any string conversion overhead.
How do you handle integer overflow when reversing a number?
In this problem, the input is constrained to be between 0 and Integer.MAX_VALUE, so overflow is not a concern. In a general setting, you would check before each multiply-and-add step whether the result would exceed the integer range, and return 0 or throw an error if it would.