不借助数组、考虑溢出
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
输入:1123456789
输出:0
解释:溢出返回0
代码
public class Question7 {
public static void main(String[] args) {
System.out.println(resulterse(563847412));
}
public static int resulterse(int x) {
int result = 0;
while (x != 0) {
int temp = x % 10;
x /= 10;
if (result > Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE / 10 && temp > 7)) return 0;
if (result < Integer.MIN_VALUE/10 || (result == Integer.MIN_VALUE / 10 && temp < -8)) return 0;
result = result * 10 + temp;
}
return result;
}
}
思路
- 32 位的整数为 int 类型
- 每次取原数的末位,通过 “乘十加末位” 来构造原数的倒序数位
- 考虑数字的溢出(超过最大数,小于最小数)
- 判断溢出时,需要在上一步 “乘十” 之后就进行判断,具有前瞻性
- 其中最后一位,还要根据具体的最大数(最小数)进行判断
注意
- Integer.MAX_VALUE 为 java 中 int 最大的数,为 2147483647
- Integer.MIN_VALUE 为 java 中 int 最小的数,为 -2147483648
- java 中的 int 类型占 4 个字节(32位)