Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Solution: 注意overflow,还要Integer.MIN_VALUE和MAX VALUE值不同
public int reverse(int x) {
int sign = 1;
if (x < 0) {
sign = -1;
}
long temp = Math.abs((long)x), ans = 0;
while (temp != 0) {
ans = ans * 10 + temp % 10;
if (ans > Integer.MAX_VALUE && sign == 1 || ans - 1 > Integer.MAX_VALUE && sign == -1) {
return 0;
}
temp /= 10;
}
return (int)(sign * ans);
}
其实可以直接result = (result*10) + (x%10),不用取绝对值
public int reverse(int x) {
long result =0;
while(x != 0)
{
result = (result*10) + (x%10);
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) return 0;
x = x/10;
}
return (int)result;
}
不用long: If overflow exists, the new result will not equal previous one.
public int reverse(int x)
{
int result = 0;
while (x != 0)
{
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result)
{ return 0; }
result = newResult;
x = x / 10;
}
return result;
}