[Algorithm problem solution] LeetCode 9. Palindrome number

topic

Determine whether an integer is a palindrome. The palindrome number refers to the same integer in both positive order (from left to right) and reverse order (from right to left).
Advanced:
Can you solve this problem without converting integers to strings?

Solution one

Convert to a string to determine whether it is a palindrome string.

class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) {
            return false;
        }
        String str = String.valueOf(x);
        int length = str.length();
        for(int i = 0; i < length / 2; i++) {
            if(str.charAt(i) != str.charAt(length - 1 - i)) {
                return false;
            }
        }
        return true;
    }
}

Solution two

Decompose each digit of the number, convert it to an array, and then judge

class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) {
            return false;
        }
        int[] digit = new int[10];
        int i = 0;
        while(x > 0) {
            digit[i++] = x % 10;
            x = x / 10;
        }
        for(int j = 0; j < i / 2; j++) {
            if(digit[j] != digit[i - 1 - j]) {
                return false;
            }
        }
        return true;
    }
}

Solution three only reverse half of the numbers for comparison

The first two methods use conversion strings, and use additional arrays. In fact, there is a better solution. We can only invert the last half of the number. If it is consistent with the first half after the inversion, it means that it is a palindrome number.

As we all know, you can use the remainder of dividing by 10 + dividing by 10 to get the last digit. So how do we judge that half of the digits have been converted? In fact, in the process of conversion, the resulting number is constantly getting bigger, but the original number is constantly getting smaller. When the original number is less than or equal to the result number, it means that half\or half plus 1 is converted (in the case of odd number of digits).

Another thing to note is the above-mentioned process of reversing the number. It is unnecessary for multiples of 10 (multiples of 10 are not palindrome numbers except 0), and it is easy to make mistakes in the special processing of odd digits in the last step. Therefore, multiples of 10 can be treated as special cases like negative numbers.

class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

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

        return (revert == x) || (revert / 10 == x);
    }
}

Guess you like

Origin blog.csdn.net/vxzhg/article/details/106673516