LeetCode 7. Reverse Integer
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1]
, then return 0.
method
INT_MIN = -21,4748,3648
INT_MAX = 21,4748,3647
最大最小数都是十位数,如果一个9位数已经比INT_MAX / 10 = 21,4748,364
还大了,那再加任何一位数都会溢出
虽然等于INT_MAX / 10
也可能会溢出,比如21,4748,3649
,但是注意原数是在整数范围内的,所以并不会出现这种情况,最大也只能是1463847412
- 要先判断再加数
int reverse(int x) {
int num = 0;
while (x) {
if (num < (INT_MIN / 10) || num > (INT_MAX / 10)) return 0;
num = num * 10 + x % 10;
x /= 10;
}
return num;
}