it is actually somewhat related to the question Reverse Integer leetcode -- how to handle overflow, to reverse digits of an integer, while returning 0 when the reversed integer overflows.
so it is supposed to be:
input: -123, return: -321
input:1500032455, return: 0
I could reverse the digits for the normal case but not the overflow case, I checked with the link above, mine is a little bulky..but I guess it should work the same? Could anyone advise?
public int reverse(int x) {
boolean isPositive = true;
if (x < 0){
isPositive = false;
x = x * -1;
}
int length = String.valueOf(x).length();
int[] digit = new int[length];
for (int i = 0; i < length; i++){
digit[i] = x % 10;
x = x / 10;
}
int solution = 0;
for (int j = 0; j < length; j++){
solution = solution + digit[length-j-1] * (int) Math.pow(10,j);
}
if (solution > Integer.MAX_VALUE){
return 0;
}
return (isPositive == false) ? -solution : solution;
}
}