[leetcode algorithm - determine the number of palindromes]

1, Title Requirements

*Determines whether an integer is a palindrome. Palindromes are integers that are read in the same positive (left to right) and reverse (right to left) order.
* example 1:
*
*Input: 121
*Output: true
* example 2:
*
*Input: - 121
*Output: false
*Explanation: read from left to right, it is - 121. Read right to left, 121 -. So it's not a palindrome number.

2, train of thought

Since we compare, we separate them from the middle and compare them one by one, using the dichotomy we used last time.

static boolean isPalindrome(int x) {
        String s = String.valueOf(x);
        char[] chars = s.toCharArray();
        int left = 0,right = chars.length-1;
        int mid = (left + right) / 2; // Be careful
        int yushu = (left + right) % 2;
        if (yushu > 0){
            left = mid ;
            right = mid + 1;
        }else {
            left = right = mid;
        }
        while (left <= right && left >-1){
            char aChar = chars[left];
            char bChar = chars[right];
            if (aChar == bChar ){
                left--;
                right++;
            }else {
                return false;
            }
        }
        return true;
    }
//Brute force, based on the same number of palindromes
    static boolean isPalindrome2(int x){
        long y = 0;
        int tmp = x;
        if (x < 0) {
            return false;
        }
        while (tmp != 0) {
            int n = tmp % 10;
            tmp /= 10;
            y = y * 10 + n;
        }
        if (x == y) {
            return true;
        } else {
            return false;
        }
    }
    //Official solution
    static boolean IsPalindrome3(int x) {
        // exceptional case:
        // As mentioned above, when x < 0, X is not a palindrome number.
        // Similarly, if the last digit of the number is 0, in order to make the number palindrome,
        // The first digit should also be 0
        // Only 0 satisfies this property
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }

        // When the length of the number is odd, we can remove the number in the middle by revertedNumber/10.
        // For example, when the input is 12321, at the end of the while loop we can get x = 12, revertedNumber = 123,
        // Since the number in the middle does not affect palindrome (it is always equal to itself), we can simply remove it.
        return x == revertedNumber || x == revertedNumber/10;
    }

Welcome to correct!

Tags: Programming

Posted on Wed, 19 Feb 2020 12:39:34 -0500 by soccerstar_23