Leetcode - 7. 整数反转

解题思路参考代码中的注释:
class Solution {
    
    private static int threshold = Integer.MAX_VALUE / 10;

    // 检查sum * 10 + num是否会超过int的表示范围
    // 如果sum大于threshold,则肯定溢出;如果sum小于threshold,则肯定不溢出
    // 如果sum正好等于threshold,则num大于7时会溢出
    private static boolean willOverflow(int sum, int num) {
        return sum != threshold ? sum > threshold : num > 7;
    }

    public int reverse(int x) {
        if (x == 0 || x == Integer.MIN_VALUE) {
            return 0;
        }
        
        // c代表x的绝对值,sign用于表示x的正负性质
        int sign = 1, c = x;
        if (x < 0) {
            sign = -1;
            c = -c;
        }
        
        // 对正整数c进行反转
        int sum = 0;
        while(c > 0) {
            int remainder = c % 10;

            // 如果会发现溢出,则直接返回0
            if(willOverflow(sum, remainder)) {
                return 0;
            }
            
            sum = sum * 10 + remainder;
            c /= 10;
        }
        
        // sum是正数,需要再乘以sign以保证最终的sum和x符号相同  
        return sum * sign;
    }
}
全部评论

相关推荐

UtopianYou...:这个简历排版真的不太行哦,去找免费的或者花点小钱,把排版弄整齐一点吧,看着舒服。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务