The title

9. A palindrome

Given an integer x, return true if x is a palindrome integer; Otherwise, return false.

Palindromes are integers that read in positive (left to right) and backward (right to left) order. For example, 121 is palindrome and 123 is not.

Example 1:

Input: x = 121 Output: trueCopy the code

Example 2:

Input: x = -121 Output: false Description: Read from left to right. The value is -121. Read from right to left, 121-. So it's not a palindrome number.Copy the code

Example 3:

Input: x = 10 Output: false Description: Read from right to left, 01. So it's not a palindrome number.Copy the code

Example 4:

Input: x = -101 Output: falseCopy the code

Idea 1:

Double pointer, converts a number to a string to an array, and then compares the head and tail each time. There is no need to deal with negative numbers, because symbols are also involved in comparisons, and negative head and tail comparisons are always false. But the solution doesn’t convert strings, so let’s post the code.

The code is as follows:

/ * * *@param {number} x
 * @return {boolean}* /
var isPalindrome = function(x) {
    let arr = String(x).split(' ');
    let len = arr.length;
    for(let i=0; i<Math.floor(len/2); i++){if(arr[i] ! = arr[len-1-i]){
            return false}}return true;
};
Copy the code

Idea 2:

If we can’t convert strings, we can actually find other ways to reverse numbers.

Such as 12321,

We’re going to take 12321%10, we’re going to get 1, we’re going to take 1232%10, we’re going to get 2, we’re going to take 123%10, we’re going to get 3

And then we upgrade, we add one operation, and every time we divide, we add a multiply by 10 operation

You take 12321%10, you get a 1 you take 1232%10, you get a 2, you multiply it by 10, you get 12 you take 123%10, you get 3, you multiply it by 10, you get 123

So at this point, we’re pretty much reversed, but until when do we stop the loop, which is halfway through the loop

If it’s even it’s just normal, if it’s odd it’s math.floor (length/2)

So, add one more operation to the above operation, divide the original number by 10 each time, so that when the original number <= inverts the number, we are actually halfway there

The other thing is to do a good boundary judgment, negative numbers, ones that are 0 and not 0 are excluded

Post a code to feel:

/ * * *@param {number} x
 * @return {boolean}* /
var isPalindrome = function(x) {
    if (x < 0 || (x % 10= = =0&& x ! = =0)) {
        return false;
    }

    let reverseNum = 0;
    while (x > reverseNum) {
        reverseNum = reverseNum * 10 + x % 10;
        x = Math.floor(x / 10);
    }
    return x === reverseNum || x === Math.floor(reverseNum / 10);
};
Copy the code