Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
如果颠倒后的数字超过Integer长度则返回0
分析:看到数字颠倒,一定要想到取余和除法。
public int reverse(int x) {
if (x == 0) {
return 0;
}
int sign = 1;
if (x < 0) {
sign = -1;
}
long number = Math.abs((long) x);
long sum = 0;
while (number != 0) {
sum = sum * 10 + number % 10;
number = number / 10;
}
if (sign * sum > Integer.MAX_VALUE || sign * sum < Integer.MIN_VALUE) {
return 0;
}
return sign * (int) sum;
}