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.

Input: x = 123
Output: 321
Input: x = -123
Output: -321
Explanation: Reversed digits of -123 is -321, which fits in 32-bit range.
Input: x = 120
Output: 21
Explanation: Trailing zero is dropped after reversal.

We extract digits one by one from the end of x and build the reversed number. Before each multiplication, we check whether the result would overflow the 32-bit signed integer bounds.

class Solution { public int reverse(int x) { long rev = 0; while (x != 0) { int digit = x % 10; x /= 10; rev = rev * 10 + digit; if (rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) { return 0; } } return (int) rev; } }
Complexity Analysis:

Time complexity: O(log x) — number of digits in x.
Space complexity: O(1) — only a few variables used.