Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Example2: x = -123, return -321
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution:
The algorithm is not difficult.Just reverse digit of the integer one by one. The tricky part is to detect the possible overflow when we reverse the integer. First, we take the absolute value of x to make reversing easier and code cleaner. Because we use multiplication and addition to reverse the integer. For detecting the overflow, we test if next possible operation would overflow before we do it. So we check if Integer.MAX_VALUE-y%10)/10<res if yes, then return MIN_VALUE or MAX_VALUE depends on its original sign. We don't have to worry about the MIN_VALUE, because Integer.MAX_VALUE = 2147483647 and Integer.MIN_VALUE= -2147483648, so if x=2137385647 or -2147483647 (although this corner case is not possible in this problem), (Integer.MAX_VALUE-y%10)/10<res) is not true, and it won't return 0; The Integer.MIN_VALUE has to be considered before Math.abs().
public int reverse(int x) {
int res=0;
boolean pos=x>0;
if(x==Integer.MIN_VALUE) return 0;
int y=Math.abs(x);
while(y!=0){
if((Integer.MAX_VALUE-y%10)/10<res) return 0;
else res=res*10+y%10;
y=y/10;
}
return (pos)? res : -res;
}
No comments:
Post a Comment