integer reversal
reverse digits algorithm
number manipulation
coding challenge
programming basics

Reverse digits of an integer

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Reversing digits of an integer is a classic interview and fundamentals problem. It tests arithmetic operations, sign handling, and boundary checks in a small piece of code. A strong solution is short, predictable, and explicit about edge cases.

Arithmetic Approach

The arithmetic method repeatedly takes the last digit and appends it to a result number. This avoids string conversion and works in languages where numeric constraints matter.

python
1def reverse_integer(n: int) -> int:
2    sign = -1 if n < 0 else 1
3    n = abs(n)
4
5    reversed_num = 0
6    while n > 0:
7        digit = n % 10
8        reversed_num = reversed_num * 10 + digit
9        n //= 10
10
11    return sign * reversed_num
12
13print(reverse_integer(12345))   # 54321
14print(reverse_integer(-9070))   # -709
15print(reverse_integer(0))       # 0

Logic summary:

  • n % 10 extracts the rightmost digit.
  • reversed_num * 10 + digit shifts left and appends.
  • n //= 10 removes the processed digit.

This is easy to reason about and runs in linear time relative to digit count.

String Approach

In scripting-heavy code, the string approach can be clearer and perfectly acceptable. You still need to handle sign and leading zeros in the reversed result.

python
1def reverse_integer_string(n: int) -> int:
2    sign = -1 if n < 0 else 1
3    s = str(abs(n))
4    reversed_s = s[::-1]
5    return sign * int(reversed_s)
6
7print(reverse_integer_string(1200))   # 21
8print(reverse_integer_string(-450))   # -54

This approach is concise and often easier for beginners, but it depends on conversion to text and back.

Handling 32-bit Overflow

Some coding platforms require returning 0 when reversed value exceeds signed 32-bit range. Add the range check after each append or once at the end.

python
1def reverse_int_32(n: int) -> int:
2    INT_MIN = -2**31
3    INT_MAX = 2**31 - 1
4
5    sign = -1 if n < 0 else 1
6    n = abs(n)
7    out = 0
8
9    while n:
10        out = out * 10 + (n % 10)
11        n //= 10
12
13    out *= sign
14    if out < INT_MIN or out > INT_MAX:
15        return 0
16    return out
17
18print(reverse_int_32(1534236469))  # 0 on 32-bit constrained tasks

For fixed-width languages, checking during the loop is safer because overflow can happen before final assignment.

Testing Strategy and Complexity

The reversal loop processes each digit once, so time complexity is linear in the number of digits and memory usage is constant for the arithmetic approach. That makes it a reliable default for constrained environments.

A minimal test set can be written quickly:

python
1cases = [
2    (123, 321),
3    (-123, -321),
4    (1200, 21),
5    (0, 0),
6]
7
8for raw, expected in cases:
9    got = reverse_integer(raw)
10    assert got == expected, f"for {raw}, expected {expected}, got {got}"
11
12print("all tests passed")

If your platform enforces fixed-width integers, add explicit boundary tests so overflow behavior is verified instead of assumed.

Common Pitfalls

A frequent mistake is ignoring negative numbers. Reversing -123 should produce -321, not 321 or an error.

Another bug is mishandling trailing zeros. Input 1200 should become 21, because integer values do not preserve leading zeros.

Using floating-point operations is also risky. Digit reversal should use integer math to avoid precision issues.

On challenge sites, many failures come from missing overflow requirements. Always read the exact constraints and implement the required return behavior.

Finally, test minimal and maximal boundaries, not only small positive samples. Boundary tests expose silent logic errors quickly.

Summary

  • Reverse digits by repeatedly extracting and appending the last digit.
  • Preserve sign separately to keep the loop simple.
  • String slicing is concise, while arithmetic is constraint-friendly.
  • Respect problem-specific overflow rules for fixed-width integers.
  • Validate with negative values, zero, trailing zeros, and boundary cases.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.