给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
我的思路:
1.先将x的各位存在数组中
2.逆序调用数组,输出反转后的结果
3.细节处理:负数就先转为正数,然后在反转后再转为负数
代码如下:
class Solution {
public int reverse(int x) {
int result = 0;
List<Integer> list = new ArrayList<>();
Boolean flag = false;
if (x < 0){
flag = true;
x = x * (-1);
}else if (x == 0){
return result;
}
while (x!=0){
list.add(x%10);
x = x/10;
}
int j = 1;
for (int i = list.size() - 1; i >= 0; i--) {
result = result + list.get(i) * j;
j = j * 10;
}
if (flag == true){
result = result * (-1);
}
return result;
}
}
问题:
没考虑大整数的问题,少一个判断
修改后的代码如下:
class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0){
if (result < Integer.MIN_VALUE/10 || result > Integer.MAX_VALUE/10){
return 0;
}
int digit = x % 10;
x = x / 10;
result = result * 10 + digit;
}
return result;
}
}
注意:之前修改时不能直接判断结果是否越界,因为系统会优先把越界的数取成2147483647,所以要在乘10之前判断