给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
实例:
输入: 123
输出: 321
- 做题的时候脑子短路了,赋值之后再去判断是否越界,res本来就是一个int遍历,赋给它一个越界的值肯定会出错呀
- int值的范围:-2147483648 ~ 2147483647 (-2^-31 ~ 2^31 - 1); 0111 1111 | 1111 1111 | 1111 1111 | 1111 1111 也就是2^31-1=2147483647 因为是正整数,所以第一位符号位是0;从1开始所以要减去全0这种情况。
- Integer.MAX_VALUE 和 Integer.MIN_VALUE
class Solution {
public int reverse(int x) {
int res = 0;
while(x != 0) {
int temp = x % 10;
x = x / 10;
// 在赋值前判断是否越界
if(res > Integer.MAX_VALUE / 10 || res < Integer.MIN_VALUE / 10) return 0;
if((res == Integer.MAX_VALUE / 10 && temp > 7) || (res == Integer.MIN_VALUE / 10 && temp < -8)) return 0;
res = res * 10 + temp;
}
return res;
}
}