Reverse Integer: the idea to remember.
Reverse a signed 32 bit integer's decimal digits, returning zero if the result overflows.
The core insight
Pop decimal digits and append them only while the reversed value remains within signed 32 bit bounds.
Why it works
Multiplying the current result by ten and adding the next digit constructs the reversed prefix exactly.
The mistake to avoid
Integer.MIN_VALUE cannot be safely negated in int. Check overflow before narrowing the result.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int reverse(int x) {
int result = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
// Reject the multiplication/addition before overflow can happen.
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && digit > 7)) return 0;
if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && digit < -8)) return 0;
result = result * 10 + digit;
}
return result;
}
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.