Maintained by Vikas Dulgunde, software engineer
You are handed one integer that fits inside a signed 32-bit slot, meaning it sits somewhere between -2^31 and 2^31 - 1. Your job is to flip the order of its digits and hand back the resulting number.
The sign stays put. A negative input produces a negative output, and any zeros that were trailing on the original simply vanish once they move to the front, since a number does not keep leading zeros.
There is one catch that makes this trickier than a plain string flip. The reversed value might be larger than what a 32-bit integer can hold. When that happens you must return 0 rather than a wrapped or truncated number.
An added rule forbids you from leaning on a wider 64-bit type to dodge the overflow. You have to detect that the answer would spill past the limit using only 32-bit-safe arithmetic, before the overflow actually occurs.
The digits 1, 2, 3 read backwards give 3, 2, 1, which is well inside range.
The minus sign is preserved and only the digit order flips.
Reversing gives 021, and the leading zero is dropped to leave 21.
The reversed value 9646324351 exceeds 2^31 - 1, so the function returns 0 instead.
Visible test cases
Pull the digits off one at a time with modulo 10 and integer division by 10. This lets you build the reversed number without converting to a string.
The sign takes care of itself if you keep the input's sign through the loop, or you can strip the sign up front and reattach it at the end.
Check for overflow BEFORE you do result = result * 10 + digit. Compare the running result against INT_MAX / 10 (and the symmetric bound for negatives) so you never actually compute a value too large to hold.
Treat the number as text, reverse the characters, parse it back to a number, then verify the result still fits in 32 bits.
Rebuild the reversed number with arithmetic only, and test against the 32-bit boundary before each multiply-and-add so overflow is caught without ever forming an out-of-range value.