# 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;
    }
}
原文地址:https://www.cnblogs.com/cnblogszs/p/13418271.html