Tips
1. INT_MIN = -2^31 = -2147483648
2. INT_MAX = 2^31-1 = 2147483647
3. If overflowing, the result of long long will be different from that of int, which can be used to do a lot.
题目
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
提示:-2^31 <= x <= 2^31 - 1
代码
代码一
int reverse(int x){
int rst = 0;
while(x){
if(rst < INT_MIN / 10 + x % 10 / 10 ||
rst > INT_MAX / 10 + x % 10 / 10){
//(x % 10 / 10)is always equal to zero, which can be omitted.
//INT_MIN = -2^31 = -2147483648
//INT_MAX = 2^31-1 = 2147483647
return 0;
}
rst = rst * 10 + x % 10;
x /= 10;
}
return rst;
}
代码二
int reverse(int x){
long long m = 0;
//If overflowing, the result of long long will be different from that of int.
while(x){
m = m * 10 + x % 10;
x /= 10;
}
return m==(int)m ? m : 0;
}