LeetCode9_Palindrome Number

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/cuidiwhere/article/details/43046459

My answer

   /**
     * case1: x is negative, x is definitely not palindrome<br>
     * <del>case2: x is between 0 and 9, x is palindrome</del>.included by case3 <br>
     * case3: x has more than 1 digit.
     *     Algorithm:
     *      step1:calculate the number of digits in X;
     *      step2: if x.len is odd, compare left-right digit; 
     *             if x.len is even, compare mid-1 and mid digit before compare left-right digit,
     */
     public boolean isPalindrome(int x) {</span>
        if (x < 0) {
            return false;
        }

        int len = 1;
        int quotient = x;
        while (quotient / 10 > 0) {
            len++;
            quotient = quotient / 10;
        }

        int mid = len / 2;
        if (len % 2 == 0) {
            int leftDigit = x / (int) Math.pow(10, len - mid) % 10;
            int rightDigit = x / (int) Math.pow(10, len - 1 - mid) % 10;

            if (leftDigit != rightDigit) {
                return false;
            } else {
                return isPalindrome(x, len, mid - 2, mid + 1);
            }

        } else {
            return isPalindrome(x, len, mid - 1, mid + 1);
        }

    }

    private boolean isPalindrome(int x, int len, int left, int right) {
        while (left >= 0 && right < len) {
            int leftDigit = x / (int) Math.pow(10, len - 1 - left) % 10;
            int rightDigit = x / (int) Math.pow(10, len - 1 - right) % 10;
            if (leftDigit != rightDigit) {
                return false;
            }

            left--;
            right++;
        }

        return true;
    }


Summary

1. 负数例如-3,-123,一定不是palindrome

2. 不能把integer 转为string,因为题目要求without extra space

3. 不能将integer reverse后再判断,因为reverse可能会out of range,例如INT_MAX=2147483647, reverse后溢出了。

4. 如何计算integer x有多少位?

    

        int len = 1;
        int quotient = x;
        while (quotient / 10 > 0) {
            len++;
            quotient = quotient / 10;
        }

5. 如何得到每一位数?

    先把该位移动到个位,再%10,见方法:private boolean isPalindrome(int x, int len, int left, int right)

猜你喜欢

转载自blog.csdn.net/cuidiwhere/article/details/43046459