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³¹, 2³¹ - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Explanation: Trailing zeros are dropped
Example 4:
Input: x = 1534236469
Output: 0
Explanation: Reversed would be 9646324351, which overflows
We reverse the integer digit by digit using modulo and division operations.
Key Steps:
digit = x % 10result = result * 10 + digitx = x // 10Overflow Detection:
[-2147483648, 2147483647]result = result * 10 + digitresult > MAX // 10 OR result == MAX // 10 and digit > 7result < MIN // 10 OR result == MIN // 10 and digit < -8Time Complexity: O(log x)
Space Complexity: O(1)
2147483647 → overflow-2147483648 → overflowExample: x = 123
Step 1: digit = 3, result = 0 * 10 + 3 = 3, x = 12
Step 2: digit = 2, result = 3 * 10 + 2 = 32, x = 1
Step 3: digit = 1, result = 32 * 10 + 1 = 321, x = 0
Result: 321
Example: x = -123
Step 1: digit = 3, result = 0 * 10 + 3 = 3, x = -12
Step 2: digit = 2, result = 3 * 10 + 2 = 32, x = -1
Step 3: digit = 1, result = 32 * 10 + 1 = 321, x = 0
Result: -321 (apply negative sign)
1/**
2 * Reverse Integer
3 * Time: O(log x) - number of digits
4 * Space: O(1)
5 */
6
7class Solution {
8 public int reverse(int x) {
9 int result = 0;
10
11 while (x != 0) {
12 int digit = x % 10;
13 x /= 10;
14
15 // Check overflow before multiplying by 10
16 // For positive: result > MAX / 10 or (result == MAX / 10 and digit > 7)
17 // For negative: result < MIN / 10 or (result == MIN / 10 and digit < -8)
18 if (result > Integer.MAX_VALUE / 10 ||
19 (result == Integer.MAX_VALUE / 10 && digit > 7)) {
20 return 0;
21 }
22 if (result < Integer.MIN_VALUE / 10 ||
23 (result == Integer.MIN_VALUE / 10 && digit < -8)) {
24 return 0;
25 }
26
27 result = result * 10 + digit;
28 }
29
30 return result;
31 }
32}
33