又开始刷题了,最近在刷这题
给你一个 32 位的有符号整数 x
,返回将 x
中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1]
,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
x=1534236469
输出0;
需要考虑溢出的情况,个人觉得可以不用 Long 来写,毕竟需要占额外的内存分配
//第一次写,没判断仔细
public static int reverse(int x) {
boolean isNegative = x < 0;
int result = 0;
int position = Math.abs(x);
while(position!=0){
int temp = position % 10;
if(result>(Integer.MAX_VALUE-temp)/10){
return 0;
}
System.out.println("temp:"+temp);
position = position / 10;
result = result * 10 + temp;
}
return isNegative?-result:result;
}
// 这个方法太巧妙了,前人栽树,后人乘凉
public int reverse(int x) {
int result = 0;
while(x != 0) {
int tmp = result; // 保存计算之前的结果
result = (result * 10) + (x % 10);
x /= 10;
// 将计算之后的结果 / 10,判断是否与计算之前相同,如果不同,证明发生溢出,返回0
if (result / 10 != tmp) return 0;
}
return result;
}
int reverse(int x){
int max = 0x7fffffff;
long b = 0;
while (x != 0) {
b = b * 10 + x % 10;
x = x / 10;
}
return (b > max || b < (-1 * (max + 1))) ? 0 : b;
}