Given a 32-bit signed integer, reverse digits of an integer.
public int reverse(int x) {
long reverse = 0;
boolean negative = false;
if (x < 0) {
negative = true;
x *= -1;
}
while (x != 0) {
int lastDigit = x % 10;
reverse = reverse * 10 + lastDigit;
x = x / 10;
if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) {
reverse = 0;
break;
}
}
if (negative) {
reverse *= -1;
}
return (int)reverse;
}