Reversing the digits of a number is a classic programming challenge. However, when working in environments constrained to 32-bit signed integers (range [-2,147,483,648, 2,147,483,647]), reversing a number can easily push the value outside bounds, causing a mathematical overflow. In Java, this triggers silent wrap-arounds (e.g. going from positive to negative).
In this guide, we will look at how to reverse a number digit-by-digit and check for overflow boundaries before performing operations.
Imagine a car odometer that only has 5 digits (can only show up to 99,999):
- If you have 99,990 miles and drive 15 more miles, the odometer rolls over to show **00,005**. It rolled over because it exceeded the physical register limits.
- In software, if we reverse `1,534,236,469` (within limits), it becomes `9,646,324,351`, which rolls over a 32-bit register and crashes calculation accuracy. We must predict this roll-over before multiplying.
1. The Reverse Logic
To reverse a number, we peel off the last digit using modulo 10 (num % 10) and add it to our running total, multiplying the previous total by 10 first:
int temp = num % 10;
ans = (ans * 10) + temp;
num = num / 10; // Discard last digit
2. Guarding Against Overflow
Before running ans * 10, we check if the operation will exceed Integer.MAX_VALUE (2147483647) or fall below Integer.MIN_VALUE (-2147483648) when divided by 10:
if (ans <= Integer.MIN_VALUE / 10 || ans >= Integer.MAX_VALUE / 10) {
return 0; // Return 0 as specified by LeetCode constraint
}
Java Implementation
Below is the complete solution in Java:
package io.practise.leetcode.medium;
public class ReversingInteger {
public static void main(String[] args) {
int num = 123678;
int ans = 0;
for (; num > 0; num = num / 10) {
// Check overflow limits before multiplying by 10
if (ans <= Integer.MIN_VALUE / 10 || ans >= Integer.MAX_VALUE / 10) {
ans = 0;
break;
}
int temp = num % 10;
ans = (ans * 10) + temp;
}
System.out.println("Reversed: " + ans); // Reversed: 876321
}
}
Conclusion
When solving arithmetic LeetCode puzzles, bounds check constraints are always the primary edge cases. Checking variables against Integer.MAX_VALUE / 10 before multiplying prevents math overflow corruption.