Leetcode 0007. 整数反转

# 题目描述

Leetcode 0007. 整数反转_第1张图片

# 题目思路

先转换为正整数后,之后一边从小到大逐层求出个十百等数,一边高位到低位逐项累加计算和
注意中间需要先将中间的和设置为long,方便中间进行判断上限,若是超过了上限了,就赋值为0

# 题目解法

/*
 * @lc app=leetcode.cn id=7 lang=java
 *
 * [7] 整数反转
 */
class Solution {
    public int reverse(int x) {
        if(x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE || x == 0){
            return 0;
        }
        boolean isContainMulFlag = false;
        if(x < 0){
            x = 0 - x;
            isContainMulFlag = true;
        }
        long sum = 0;
        while(x / 10 != 0){
            sum = (sum + x%10)*10;
            x = x/10;
            if(sum >= Integer.MAX_VALUE){
                return 0;
            }
        }
        sum = sum + x;
        if(isContainMulFlag){
            sum = 0 - sum;
        }
        if(sum <= Integer.MIN_VALUE){
            return 0;
        }
        return (int)sum;
    }
}


class Test{
    public static void main(String[]args){
        Solution s = new Solution();
        int result = s.reverse(-2147483648);
        System.out.println(result);
    }
}

你可能感兴趣的:(leetcode)