Search code examples
variablesnumberspalindrome

Palindrome of a number - No console log


So I tried to write a code that finds the largest palindromic number from two (3 spaces long) multiplied numbers. Does my code work fine or are there no palindromes for this?

function checkPalindrom(str) {
    return str === str.split('').reverse().join('');
}; //Declares the funciton to check if a string is a palindrome

var x = 999;
var y = 999;
var z = 0;
var n = z.toString(); //Declares that n is the string of z

for (i=0; i<899; i++) { //For loop: counts from 0 to 899
    x*y===z; //Is this correct? z is set equal to x*y
        if(checkPalindrom(n) === true) { //If n is a palindrome,
            console.log(n); //Write out the palindrome
        } else {
            x-=1; //subtract 1 from x and run again
        }
};

Also, what is the best way to check for all combinations of 3 digit numbers? Because right now I am just checking for any number from 100 to 999, but I actually need to check for all combinations...


Solution

  • Your post has a few problems, as well as multiple questions in it. I'll try to hone in on the major stuff but, as this is a fairly standard type of Programming 101 homework question, I'm not going to give you an exact answer right out.

    First off, there are three different 'equals' in javascript, =, ==, and ===. A single = is an assignment operator and it always works from right to left. Thus,

        var x = 2;
    

    assigns the value of 2 to the variable x. In your code,

        x*y === z;
    

    has a couple of problems. First off, it is backwards. Secondly, it uses === but should be using =.

        z = x*y;
    

    That is what you were trying to put here.

    In javascript, == and === are both comparitives. The triple === adds type comparison and is stronger but generally unnecessary. In almost all cases, == is sufficient. But, what it does is compare the values like inside an if statement:

        if(x == 2)
    

    This just checks if the value of x is equal to the value of 2, but the values themselves do not change.

    Ok, for your other question: "number from 100 to 999, but I actually need to check for all combinations..."

    The best way to handle this is a double loop:

        var z;
        for(var x = 100; x < 1000; x++)
            for(var y = x; y < 1000; y++)
               z = x*y;
    

    This will first let x = 100, then check 100 * every number from 100 to 999. Then you let x = 101 and check 101* every number from 101 to 999.