Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Example2: x = -123, return -321
Overflow!!!
public int reverse(int x) {
if(x == Integer.MIN_VALUE) return 0;
int sign = 1;
if(x < 0){
sign = -1;
x = -x;
}
int ans = 0;
while(x != 0){
int d = x%10;
if(ans <= (Integer.MAX_VALUE - d)/10)
ans = ans * 10 + d;
else
return 0;
x/=10;
}
return sign*ans;
}
没有评论:
发表评论