Kaitian Xie
Posted on April 10, 2019
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) {
return 0;
}
if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) {
return 0;
}
rev = rev * 10 + pop;
}
return rev;
}
Reversing an integer is similar to reversing String. We get the last digit x % 10
and add it to rev
. We repeat this process until x
is 0. The two if statements are used to prevent integer overflows.
Time Complexity: O(log(x))
Extra Space: O(1)
A note on integer overflows
A integer occurs when the sum of rev * 10 + pop
is greater/less than the maximum value (Integer.MAX_VALUE
)/the minimum value(Integer.MIN_VALUE
). So we need the check the values of rev
and pop
.
- If
rev > Integer.MAX_VALUE/10
orrev < Integer.MIN_VALUE/10
,rev * 10 + pop
will overflow. - If
rev == Integer.MAX_VALUE / 10
,pop
must be less than or equal to 7 because2^32 - 1 % 10 == 7
. - If
rev == Integer.MIN_VALUE / 10
,pop
must be greater than or equal to -8 because-2^32 % 10 == 8
.
💖 💪 🙅 🚩
Kaitian Xie
Posted on April 10, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
datascience Data Science vs Machine Learning: Which Should You Master for the AI Boom?
November 18, 2024