题目描述:
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.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
-2^31 <= x <= 2^31 -1
Time complexity: O(logn)
只使用int 记录:
- 依次从右往左计算出每位数字,然后逆序累加在一个整数中
- 在每次累加操作之前,需要判断累加后是否会越出int范围。当res > 0时,若 res * 10 + x % 10 > INT_MAX,等价于res > (INT_MAX - x % 10) / 10,若成立,则超出范围(注意,这里x是正数)
当res < 0时,若 res * 10 + x % 10 < INT_MIN,等价于res < (INT_MIN - x % 10) / 10,若成立,则超出范围(注意,这里x是负数)
class Solution {
public int reverse(int x) {
int res = 0;
while(x != 0){
if(res > 0 && res > (Integer.MAX_VALUE - x % 10)/10) return 0;
if(res < 0 && res < (Integer.MIN_VALUE - x % 10)/10) return 0;
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
}