不借助數組、考慮溢出
示例 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位)