LeetCode ---- 7、整数反转

题目链接

思路:从这个数的末尾向前开始计算,准备一个变量result进行存储结果,每次取出的末尾数记为tail,tail=num % 10,result=result*10 + tail。注意:在进行result*10计算之前,应该先判断是否会溢出,若会溢出,则直接返回0。

    public int reverse(int x) {
        if (x == Integer.MIN_VALUE) {
            return 0;
        }
        boolean neg = false;
        if (x < 0) {
            neg = true;
        }
        x = Math.abs(x);
        int result = 0;
        int tail = 0;
        while (x != 0) {
            tail = x % 10;
            if (result > Integer.MAX_VALUE / 10) {
                return 0;
            }
            result = result * 10 + tail;
            x /= 10;
        }
        return neg ? -result : result;
    }
发布了7 篇原创文章 · 获赞 0 · 访问量 12

猜你喜欢

转载自blog.csdn.net/sinat_34679453/article/details/105555437