LeetCode:整数反转(Reserve Integer)

public class ReserveInteger {
    public int reverse(int x) {
        //用于接收个位数(10的余数)
        int remainder;
        //是否负数
        int isMinus = 0;
        //存储结果
        double result = 0;
        //获得整数长度
        int length = ("" + x).length();
        if (x < 0) {
            isMinus = -1;
        }
        //遍历整数的每一位,如果是负数就少遍历一次
        for (int i = 0; i < length + isMinus; i++) {
            //取得个位数(带符号)
            remainder = x % 10;
            //取得反转数
            result = result * 10 + remainder;
            //去掉个位数
            x /= 10;
        }
        //判断是否值范围,返回反转数
        return (int) (result <= Integer.MAX_VALUE && result >= Integer.MIN_VALUE ? result : 0);
    }
}

猜你喜欢

转载自www.cnblogs.com/wymc/p/10050729.html
今日推荐