# leetcode[7. 整數反轉]
阿新 • • 發佈:2020-08-02
leetcode
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; } }