Reverse the digits of a signed 32-bit integer, returning 0 if the reversed value would overflow.
Problem
Given a signed 32-bit integer x, reverse its decimal digits and return the resulting integer.
- If
xis negative, preserve the sign in the result. - Leading zeros in the reversed number should be removed automatically.
- If the reversed value does not fit in the signed 32-bit range
[$-2^{31}$, $2^{31}-1$], return0.
Implement the reversal without using string conversion if possible; the core challenge is handling overflow safely while rebuilding the number digit by digit.
Input Format
- A single integer
x.
Output Format
- Return the reversed integer, or
0if the result overflows 32-bit signed integer range.
Constraints
- The result must also fit in the same range, otherwise return
0.
Hints
- Extract digits one at a time using
% 10and/ 10. - Check for overflow before multiplying by 10 and adding the next digit.
- Be careful with negative values and languages where integer division truncates toward zero.
Input Format
A single signed 32-bit integer x.
Output Format
The reversed integer, or 0 if reversing x would overflow a signed 32-bit integer.
Constraints
- Return
0when the reversed integer is outside this range.
Example 1
Input
x = 123
Output
321
Explanation
Reversing the digits gives 321, which fits in range.
Example 2
Input
x = -120
Output
-21
Explanation
The reversed digits are 021, which becomes 21, and the sign stays negative.
Show 1 more example
Example 3
Input
x = 1534236469
Output
0
Explanation
The reversed value is 9646324351, which overflows 32-bit signed integer range, so return 0.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.