DSA problem
Reverse Integer
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], return 0 instead. You must solve this without using a 64-bit integer for the result.
The straightforward approach repeatedly peels off the last digit with x % 10 and pushes it onto a running result with result = result * 10 + digit. The arithmetic is identical for positive and negative inputs because the C-style % and / operators preserve sign in most languages.
The tricky part is overflow detection. After multiplying result by ten and adding a new digit, the value could exceed INT_MAX (2,147,483,647) or fall below INT_MIN (-2,147,483,648). We cannot wait until after the assignment to check because the overflow has already happened.
The safe approach is to test before the update: if result > INT_MAX / 10, or result == INT_MAX / 10 and the new digit is greater than 7 (the last digit of INT_MAX), the positive overflow is imminent. The symmetric test handles the negative side. If either condition triggers, return zero immediately. The whole reversal runs in O(d) time with O(1) extra space, where d is the digit count.
Examples
x = 123321x = -123-321x = 15342364690Constraints
- -2^31 <= x <= 2^31 - 1
- Do not store the result in a 64-bit integer; detect overflow with checks on the 32-bit accumulator.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.