1331. Reverse the Digits, Safely
Reverse the digits of a signed 32-bit integer, keeping the sign. If the result
does not fit in a signed 32-bit integer, print 0.
123 -> 321
-123 -> -321
120 -> 21 leading zeros disappear
1534236469 -> 0 the reversal is too large
The reversing itself is four lines. The problem is the overflow check, and it has to happen BEFORE the value that would overflow is produced. Testing afterwards is too late: in most languages signed overflow has already wrapped, or is undefined behaviour, and the test reads whatever the wrap left behind.
So check before each step. With result about to become result * 10 + digit,
the range -2147483648 .. 2147483647 is exceeded exactly when:
result > 214748364 or (result == 214748364 and digit > 7)
result < -214748364 or (result == -214748364 and digit < -8)
Alternatively, accumulate in a 64-bit integer where no wrap can happen, and compare against the 32-bit bounds at the end. That is simpler and is what the reference solutions do.
The most negative value is its own trap: its magnitude has no positive counterpart, so negating it first overflows before any reversing begins.
Constraints - `-2147483648 ≤ x ≤ 2147483647`
Input
One line containing the integer x.
Output
Print the digit reversal of x, or 0 if it does not fit in a signed 32-bit integer.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.