9. Palindrome Number


https://leetcode.com/problems/palindrome-number/

Determine whether an integer is a palindrome. Do this without extra space.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

Solution

One

Reverse half of the number

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    // negative numbers, non-zero numbers that end with 0
    if (x < 0 || (x > 0 && x % 10 === 0)) { return false }

    var y = 0
    // reverse half
    while (x > y) {
        y = y * 10 + x % 10
        x = Math.floor(x / 10)
    }

    // even and odd
    return x === y || x === Math.floor(y / 10)
};

Two

Compare from the two ends.

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    // negative numbers, non-zero numbers that end with 0
    if (x < 0 || (x > 0 && x % 10 === 0)) { return false }

    var len = 1
    while (x / len >= 10) {
        len *= 10;
    }

    while (x !== 0) {
        // left end and right end
        if (Math.floor(x / len) !== x % 10) {
            return false
        }
        // chop the left end the chop teh right
        x = Math.floor((x % len) / 10)
        len /= 100
    }

    return true
};

results matching ""

    No results matching ""