Reverse Integer

[Link] https://leetcode.com/problems/reverse-integer/
We consume the input one digit at a time, appending each signed digit to the
reversed value. Java integer division truncates toward zero, and % keeps the
dividend’s sign, so x % 10 is the signed last digit for both positive and
negative inputs. Repeated division removes that digit; zero therefore also
handles trailing zeroes without special cases.
Before multiplying the accumulated value by 10, compare it with the integer
bounds divided by 10. At the positive boundary, the last digit may be at most
7; at the negative boundary it may be at least -8. These are the final
digits of Integer.MAX_VALUE and Integer.MIN_VALUE. Rejecting a digit that
would cross either bound before multiplication prevents overflow. The invariant
is that reversed is exactly the reverse of the input digits consumed so far;
each iteration preserves it, and the checks ensure every intermediate value
fits in an int.
class Solution {
public int reverse(int x) {
int reversed = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
if (reversed > Integer.MAX_VALUE / 10
|| (reversed == Integer.MAX_VALUE / 10 && digit > 7)
|| reversed < Integer.MIN_VALUE / 10
|| (reversed == Integer.MIN_VALUE / 10 && digit < -8)) {
return 0;
}
reversed = reversed * 10 + digit;
}
return reversed;
}
}
Each iteration consumes one decimal digit, so the time complexity is
O(log |x|). Only a fixed number of integer variables are used, giving O(1)
extra space.