package leetcode.editor.cn;//給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
//
// 示例 1:
//
// 輸入: 123
//輸出: 321
//
//
// 示例 2:
//
// 輸入: -123
//輸出: -321
//
//
// 示例 3:
//
// 輸入: 120
//輸出: 21
//
//
// 注意:
//
// 假設我們的環境只能存儲得下 32 位的有符號整數,則其數值范圍為 [?231, 231 ? 1]。請根據這個假設,如果反轉后整數溢出那么就返回 0。
// Related Topics 數學public class 整數反轉 {public static void main(String[] args) {Solution solution = new 整數反轉().new Solution();System.out.println(solution.reverse(1534236469));System.out.println(-21 / 10);System.out.println(-21 % 10);}//leetcode submit region begin(Prohibit modification and deletion)class Solution {/*** 方案一:數字循環* 通過循環將數字x的每一位拆開,在計算新值時每一步都判斷是否溢出。* 溢出條件有兩個,一個是大于整數最大值 Integer.MAX_VALUE,另一個是小于整數最小值 Integer.MIN_VALUE,設當前計算結果為 num,下一位為 temp。* 從 num * 10 + temp > Integer.MAX_VALUE 溢出條件來看* 當出現 num / 10 > Integer.MAX_VALUE 且還需要添加 temp 時,一定溢出。* 當出現 num == Integer.MAX_VALUE / 10 時,且 temp > 7 時,一定溢出,7 是 Intger.MAX_VALUE 的個位數。* 從 num * 10 + temp < Integer.MIN_VALUE 溢出條件來看* 當出現 num / 10 < Integer.MIN_VALUE 且還需要添加 temp 時,一定溢出。* 當出現 num == Integer.MIN_VALUE / 10 時,且 temp < -8 時,一定溢出,-8 是 Intger.MIN_VALUE 的個位數。* @param x* @return*/public int reverse(int x) {try {int num = 0;while (x != 0) {int temp = x % 10;if (num > Integer.MAX_VALUE / 10 || (num == Integer.MAX_VALUE / 10 && temp > 7)){return 0;}if (num < Integer.MIN_VALUE / 10 || (num == Integer.MIN_VALUE / 10 && temp < -8)){return 0;}num = num * 10 + temp;x = x / 10;}if (num > Integer.MAX_VALUE || num < Integer.MIN_VALUE) {return 0;}return num;} catch (Exception e) {return 0;}}}
//leetcode submit region end(Prohibit modification and deletion)/*** 方案二:字符傳反轉* 常識:10 * -1 = -10;-10 * -1 = 10;-21 % 10 = -1;-21 / 10 = -2* 分析:判斷數字是否大于0,在利用 reverse 函數進行反轉。*/public int reverse1(int x) {try {int b = 1;if (x < 0) {x = x * -1;b = -1;}StringBuffer stringBuffer = new StringBuffer(String.valueOf(x));x = Integer.valueOf(stringBuffer.reverse().toString());x = x * b;return x;} catch (Exception e) {return 0;}}
}