all articles

leetcode war 9 - Palindrome Number

2016-10-14 @sunderls

leetCode js

https://leetcode.com/problems/string-to-integer-atoi/

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

Analysis

Since extra space is not allowed, we cannot do it with a array. Since we have did a related problem leetcode war 7 - Reverse Integer , we can calculate the reversed number, and compare them.

Code @ 2016.10.15

But direct use of leetcode war 7 - Reverse Integer failed, leetcode told me that nagative number cannot be treated as palindrome, well this is just a definition problem, and with a simple modification, following accepted solution is done in 349ms, top 30%, not very fast though.

var isPalindrome = function(x) {
    var originX = x;

    var result = 0;
    var rest = x;

    var MAX_INT = Math.pow(2,32 - 1) - 1;
    var MIN_INT = - Math.pow(2,32 - 1);

    if (x < 0){
        return false;
    }

    while(x > 0){
        rest = x % 10;
        result = result * 10 + rest;
        x = Math.floor(x / 10);
    }

    if (result > MAX_INT || result < MIN_INT){
        result = 0;
    }
    return originX === result;
};