# leetcode #[7. 整數反轉]

leetcode

7. 整數反轉

class Solution {
    public int reverse(int x) {

        boolean isNegative = false;
        if(x < 0){
            isNegative = true;
        }

        int ans = 0;
        while(x != 0){
            
            // 負數的取模仍然爲負數
            int pop = x % 10;

            // 爲了防止“ans * 10 + pop”的值可能溢出
            // 需要用Integer.MAX_VALUE 或 Integer.MIN_VALUE進行提前計算並判斷

            // 如果是正數,先提前判斷是否溢出,因爲pop大於等於0
            // 所以Integer.MAX_VALUE - pop的值仍然不會溢出
            if(!isNegative && ans > (Integer.MAX_VALUE - pop) / 10){
                return 0;
            }
            // 如果是負數,先提前判斷是否溢出,因爲pop小於0
            // 所以Integer.MIN_VALUE - pop的值大於MIN_VALUE,仍然不會溢出
            else if(isNegative && ans < (Integer.MIN_VALUE - pop) / 10){
                return 0;
            }
            // 正常情況下的翻轉邏輯
            else{
                ans = ans * 10 + pop;
            }
            x = x / 10;
        }

        return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章