Reverse Integer
LeetCode
Integer Overflow
Programming Challenges
Coding Tips

Reverse Integer leetcode -- how to handle overflow

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 an integer might seem like a straightforward task at first glance, but when you delve deeper into potential pitfalls, particularly with the risk of integer overflow, the problem becomes fascinating and complex. The LeetCode problem "Reverse Integer" challenges us to reverse a given 32-bit signed integer and return the result. However, if the reversed integer overflows, we should return 0.

This article explores efficient strategies to handle this problem while ensuring no overflow errors occur.

Problem Description

Given a signed 32-bit integer x, reverse digits of x. When reversing the integer, ensure that it does not overflow. If it does, return 0.

Input Constraints:

  • 231x2311-2^{31} \leq x \leq 2^{31} - 1 (i.e., 2,147,483,648x2,147,483,647-2,147,483,648 \leq x \leq 2,147,483,647)

Handling Overflow: The Safe Approach

When reversing an integer, an overflow will occur if the reversed integer is not storable within the bounds of a 32-bit signed integer. Let's detail potential strategies to handle this.

Strategy

To prevent overflow, we must check, before we multiply the current result by 10 and add the new digit. Here's a step-by-step breakdown:

  1. Start with a result variable initialized to 0.
  2. Iterate through each digit of x from the least significant to the most significant.
  3. Check Potential Overflow:
    • Before updating the result, check if multiplying the result by 10 will cause an overflow.
    • As the maximum value of a 32-bit integer is 2,147,483,647, when adding a new digit, ensure that result is less than 214748364 (2,147,483,647 // 10). If it equals this value, ensure the last digit is less than or equal to 7.
    • Similarly for negative numbers, ensure the result is greater than -214748364 and the last digit is less than 8.
  4. Perform the Reverse:
    • Pop the last digit from x and push it onto the reversed number result.
  5. If any step will cause overflow, return 0 immediately.

Reversing Logic

Here is the pseudocode showing how this strategy can be implemented:

python
1def reverse(x: int) -> int:
2    INT_MAX = 2**31 - 1  # 2147483647
3    INT_MIN = -2**31     # -2147483648
4    result = 0
5
6    while x != 0:
7        # Pop operation:
8        digit = x % 10 if x > 0 else -(abs(x) % 10)
9        x = x // 10 if x > 0 else (x // 10) + 1 if digit < 0 else (x // 10)
10
11        # Check if the result will overflow
12        if result > INT_MAX // 10 or (result == INT_MAX // 10 and digit > 7):
13            return 0
14        if result < INT_MIN // 10 or (result == INT_MIN // 10 and digit < -8):
15            return 0
16        
17        # Push operation:
18        result = result * 10 + digit
19
20    return result

Edge Cases

  • Handling Zeroes: An input of 0 should return 0.
  • Maximum/Minimum Values: Inputs like 2147483647 or -2147483648 should reverse safely and return 0 if they overflow.
  • Negative Numbers: Ensure that negative numbers are reversed correctly and checked for underflow.

Key Points Summary

PointExplanation
Integer LimitsHandled within $-2^&#123;31&#125;$ to $2^&#123;31&#125; - 1$.
Overflow CheckBefore updating result, ensure not to exceed range limits.
Pop OperationExtract the last digit without causing overflow.
Push OperationMultiply result by 10 safely and add last digit.
Return ZeroOn potential overflow or underflow conditions.

Additional Considerations

  • Efficiency: The algorithm runs in O(n)\mathcal{O}(n) time complexity, where n is the number of digits in the integer x.
  • Space Complexity: The solution uses O(1)\mathcal{O}(1) space, as no additional data structures are used aside from integer variables.

Conclusion

The "Reverse Integer" problem is a classic example of careful boundary condition management and provides an excellent opportunity to work with handling overflow in programming. By validating the conditions before actual arithmetic operations, we can ensure the solution stays robust and efficient.

Implementing this logic either in pseudocode or any particular programming language can deepen understanding of integer arithmetic limitations and precise control flow design in technical problem-solving scenarios.


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.