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.
Output: 321
Output: -321
Explanation: Reversed digits of -123 is -321, which fits in 32-bit range.
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.
- Pop digit:
digit = x % 10, thenx /= 10. - Before pushing: check if
rev > Integer.MAX_VALUE / 10orrev < Integer.MIN_VALUE / 10. - Push digit:
rev = rev * 10 + digit. - Return
(int) revat the end.
Complexity Analysis:
Time complexity: O(log x) — number of digits in x.
Space complexity: O(1) — only a few variables used.