[LeetCode-Java Practice] 09. Palindrome Number (Simple)

1. Title description

Insert picture description here

2. Problem solving ideas

If you look at the number of palindrome intuitively, it feels like you fold the numbers in half to see if they can correspond one by one.
So the operation of this solution is to take out the second half of the number and flip it.
First, we should deal with some critical situations. All negative numbers cannot be palindrome, for example: -123 is not a palindrome, because-is not equal to 3. So we can return false for all negative numbers. Except for 0, all numbers whose ones digit is 0 cannot be a palindrome, because the highest digit is not equal to 0. So we can return false for all numbers greater than 0 and the ones digit is 0.
One point to note here is that the number of digits of the palindrome can be odd or even, so when its length is even, it should be equal when it is folded in half; when its length is odd, then after it is folded in half, One of the lengths needs to be removed by one digit (divide by 10 and round up).
The specific method is as follows:
each time the remainder operation (%10) is performed, the lowest number is taken out: y = x% 10
The lowest number is added to the end of the number taken out: revertNum = revertNum * 10 + y
every time a lowest digit is taken, x must be divided by 10 to
determine whether x is less than revertNum. When it is less, it means that the number has been half or more than half.
Finally, determine the odd and even number: if it is an even number, revertNum and x are equal; if it is an odd number, The middle number is at the lowest bit of revertNum. Divided by 10, it should be equal to x.

3. Code implementation

class Solution {
    
    
    public boolean isPalindrome(int x) {
    
    
        if (x < 0 || (x % 10 == 0 && x != 0)) return false;
        int revertedNumber = 0;
        while (x > revertedNumber) {
    
    
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        return x == revertedNumber || x == revertedNumber / 10;
    }
}

Guess you like

Origin blog.csdn.net/weixin_48683410/article/details/113391721