leetcode (Reverse Integer)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85255272

Title:Palindrome Number    7

Difficulty:Easy

原题leetcode地址:  https://leetcode.com/problems/reverse-integer/

1.   见代码注释

时间复杂度:O(1)。

空间复杂度:O(1)。

    /**
     * StringBuffer,注意临界值
     * @param x
     * @return
     */
    public static int reverse(int x) {

        String string = Integer.toString(x);
        if (x < 0) {
            string = string.replace("-", "");
        }
        StringBuffer stringBuffer = new StringBuffer(string);
        String result = stringBuffer.reverse().toString();
        if(Long.parseLong(result) > Integer.MAX_VALUE) {
            return 0;
        }
        return x > 0 ? Integer.parseInt(result) : - Integer.parseInt(result);

    }

1.   见代码注释

时间复杂度:O(n),一次一层while循环。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 整除和求余交换,注意临界值
     * @param x
     * @return
     */
    public static int reverse1(int x) {

        long xx = x;
        if (xx < 0) {
            xx *= -1;
        }
        long result = 0;
        while (xx > 0) {
            result *= 10;
            result += xx % 10;
            xx /= 10;
        }

        if (result > Integer.MAX_VALUE) {
            return 0;
        }
        int res = (int)result;
        
        return (x < 0 ? res * -1 : res);
        
    }
扫描二维码关注公众号,回复: 4681393 查看本文章

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85255272