思路:
例:
1.先将整数x 取余10,得到个位数,再得到除了个位数之外的整数,
2再重复操作,这次将上次得到的个位数乘10,再加上这次得到的个位数,如此便将原来最小的位数变成最大的位数;
3.依次将x中的数取出,加到反转的数中,得到结果。
实现:
1.先定义一个变量result接收反转后的结果,并将其先取0。
2.利用循环,将x%10得到整数x中的个位数,将result*10+x%10赋值给result,再让x/10,得到除了个位数之外的整数,循环至x=0。
3.题中要求对反转后的数是否合理进行判断:
即反转后的数不得超过int表示的范围,可用Integer.MAX_VALUE函数和Integer.MIN函数代表最大和最小值,再用if语句进行判断。
Integer.MAX_VALUE = 2^31-1=2147483647
Integer.MIN_VALUE = -2^31=-2147483648
if代码实现:
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE/10 && x % 10 > 7)) {
return 0;
}
if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE/10 && x % 10 < -8)) {
return 0;
}
完整代码:
class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0) {
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE/10 && x % 10 > 7)) {
return 0;
}
if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE/10 && x % 10 < -8)) {
return 0;
}
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
}