JavaScript Optimal verification if a number is Palindrom in JS

I have a problem I am sitting on for the past few days.

I want to write an optimal (in JS) program for verifying if a number is a Palindrome.

My current approach:

function isPalidrom2(pali){
//MOST time consuming call - I am splitting the digit into char array. 
  var digits = (""+pali).split("");
//To get the length of it. 
  var size = digits.length;
  var isPali = true;
  for(var i = 0; i<Math.floor(size/2); i++){
    //I am comparing digits (first vs last, second vs last-1, etc.) one by one, if ANY of the pars is not correct I am breaking the loop. 
    if(parseInt(digits[i]) != parseInt(digits[size-i-1])){
      isPali = false;
      break;
    }
  }
  return isPali;
}
Answer:1

To keep the spirit of you code, you could exit the loop with return instead of break and use the string directly without converting to an array. Strings have, as arrays, the possibility of an access single character with an index.

function isPalidrom2(value) {
    var digits = value.toString(),
        length = digits.length,
        i, l;

    for (i = 0, l = length >> 1; i < l; i++) {
        if (digits[i] !== digits[length - i - 1]) {
            return false;
       }
    }
    return true;
}

console.log(isPalidrom2(1));
console.log(isPalidrom2(12));
console.log(isPalidrom2(1221));
console.log(isPalidrom2(123));
Answer:2

If you're trying to speed things up, you could shave a few more seconds off by optimising your isPrime(n) function.

  • You don't need to check every factor, only the prime factors less than sqrt(n)
  • If you check every number from 2 to 99999 in ascending order, you can store the results as you go, so you don't need to keep re-calculating the list of previous primes

Something like this:

var savedPrimes = [2]

function isPrime(n){
    // call this method with increasing values of n (starting at 2), saving primes as we go,
    // so we can safely assume that savedPrimes contains all primes less than n
    for(var i=0; i<savedPrimes.length; i++)
    {
        var f = savedPrimes[i];
        if ((n % f) == 0)
            return false; // found a factor
        if (f*f>=n)
            break; // stop checking after f >= sqrt(n)
    }
    // no prime factors - we found a new prime
    savedPrimes.push(n);
    return true;
}


function get5DigitPrimeNr(){
    var a5DigitsPrime = [];
    var i;

    // first find all the primes less than 10000
    for(i = 3; i<10000; i++){
        isPrime(i);
    }

    // now find (and keep) the rest of the primes up to 99999
    for(i = 10000; i<100000; i++){
        if(isPrime(i)){
            a5DigitsPrime.push(i)
        }
    }
    return a5DigitsPrime;
}

EDIT - when I run your code with this method, I get a time of 10 sec

Answer:3

I have an web project where I'd like to animate the opacity of five colored divs causing them to "blink" in sequence, and the user would then click on them in the same order (like Simon says). The ...

I have an web project where I'd like to animate the opacity of five colored divs causing them to "blink" in sequence, and the user would then click on them in the same order (like Simon says). The ...

so I have a time-stamp function in a javascript file that return a date that look like MM/DD/YY I would like tom import what the function return into another script ( node.js) and display it whenever ...

so I have a time-stamp function in a javascript file that return a date that look like MM/DD/YY I would like tom import what the function return into another script ( node.js) and display it whenever ...

I need to merge a Map instance w/ an object. This didn't work: > map = new Map([ ['foo', 1] ]) Map { 'foo' => 1 } > Object.assign({}, map) {} Looks like Object.assign doesn't like maps. Is ...

I need to merge a Map instance w/ an object. This didn't work: > map = new Map([ ['foo', 1] ]) Map { 'foo' => 1 } > Object.assign({}, map) {} Looks like Object.assign doesn't like maps. Is ...

I have JSON array that looks like var data = { "fields": [{ "firstName": { "fieldName": "First Name", "required": true, "provided": false } }, { "...

I have JSON array that looks like var data = { "fields": [{ "firstName": { "fieldName": "First Name", "required": true, "provided": false } }, { "...