简体   繁体   中英

Javascript function that checks whether number is palindrome

I read through a few of palindrome questions posted here, but unfortunately couldn't find a way to fix mine. An example of what I'm trying to achieve:

Input: 989
Output: "It's a palindrome"

Input: 23
Output: "Not a palindrome"

Input: 9 
Output: "It's a palindome" (any single digit)

My try

function Palindrome(num) { 

  let numToStringArray = num.toString().split('');
  let reversedArray = numToStringArray.reverse();


  if (num.toString().length<2) {
     return "It's a palindrome"
  }
  else { 
        for (let i = 0; i<numToStringArray; i++;) {    
           if (numToStringArray[i] !== reversedArray[i]) {
             return "It's not a palindrome"
             }
            else {
                 return "It's a palindrome"
                 }
             }
        } 
}

When invoked, the function only works for single-digit strings. I tried to fix my for-loop, as I feel that the problem lies in the following line:

 if (numToStringArray[i] !== reversedArray[i])

but could not come up with a working solution. Thanks for reading or even helping me out!

I'm spotting several problems...

First, you don't want a ; after your i++ in the loop definition. In jsFiddle at least, that's resulting in a syntax error. Other environments may be more forgiving, but it's worth fixing.

Second, the loop condition is wrong:

i < numToStringArray

should be:

i < numToStringArray.length

Third, the logic of the loop is a bit broken. You're returning "It's a palindrome" immediately if the very first pair match. So by that logic "1231" is a palindrome. Instead, only return within the loop if you find that it's not a palindrome. If the loop completes without returning, then return that it's a palindrome:

for (let i = 0; i < numToStringArray.length; i++) {
    if (numToStringArray[i] !== reversedArray[i]) {
        return "It's not a palindrome";
    }
}
return "It's a palindrome";

Made this quick & working solution:

function checkPalindrome(num) {
    var numString = num.toString();
    return numString.split("").reverse().join("") == numString;
}

Provide an integer parameter inside the checkPalindrome() function, and it will return either true or false .

For example:

if (checkPalindrome(123321)) {
    console.log("Is a palindrome");
} else {
    console.log("Not a palindrome");
}

How about this

str === str.split('').reverse().join("")

like so

 const palindrome = num => { const str = num.toString(); return `It's ${str.length<2 || str === str.split('').reverse().join("")? "": "not "}a palindrome` }; console.log( [989, 23, 9].map(num => `${num}: ${palindrome(num)}`) )

actually your numToStringArray is not reversing. Try this:

function Palindrome(num) { 
      
      let numToStringArray = num.toString().split('');
      let reversedArray = num.toString().split('').reverse();
    
    console.log("here", numToStringArray, reversedArray)
      if (num.toString().length<2) {
         return "It's a palindrome"
      }
      else { 
            for (let i = 0; i<numToStringArray.length; i++) {    
               if (numToStringArray[i] !== reversedArray[i]) {
                 return "It's not a palindrome"
                 }
                else {
                     return "It's a palindrome"
                     }
                 }
            } 
    }
    
    console.log(Palindrome(686))

The reason your logic doesn't is mainly due to the fact that you use i < numToStringArray instead of i < numToStringArray.length as mentioned in the comments.

The simplest way to achieve what you want though, would simply be-

function isPalindrome(num) { 
  return num === Number(num.toString().split('').reverse().join(''));
}

Taking advantage of its function, something you could do after using the split method and the reverse method to read the number from right to left, is to use the join to transform it into a string again and then compare them, like this:

 function Palindrome(num) { let numToStringArray = num.toString().split(''); let reversedArray = numToStringArray.reverse().join(''); if (num.toString() == reversedArray) console.log('It\'sa palindrome'); else console.log('It\'s not a palindrome'); } Palindrome(9); Palindrome(232); Palindrome(152);

This should work.

const pal = num => {
  let reversedNum =  parseFloat(num.toString().split('').reverse().join(''));
  if (reversedNum === num) {
    console.log("palindrome")
  } else {
    console.log("no palindrome")
  }
}

pal(12121);

Without using split , reverse and join , it can be checked through a single array.

 function Palindrome(num) { let numToStringArray = num.toString(); var len = numToStringArray.length; if (len < 2) { return "It's a palindrome" } else { for (var i = 0; i < len / 2; i++) { if (numToStringArray[i];== numToStringArray[len - 1 - i]) { return "It's not a palindrome". } return "It's a palindrome" } } } console;log(Palindrome(989)). console;log(Palindrome(23)). console;log(Palindrome(9));

A short function to test if the number is a Palindrome and returns a "true" or "false" is as follows:

You can then call it and output your text result "It's a palindrome" in case it returns true or "Not a palindrome" if returns false.

Test examples provided below.

 const IsPalindrome = e => (e+="").split("").reverse().join("") == e; // ======== test ============= console.log(IsPalindrome(23)); // false console.log(IsPalindrome(121)); // true console.log(IsPalindrome(9889)); // true console.log(IsPalindrome(989)); // true console.log(IsPalindrome(1)); // true

To meet your specific requirements for the output text. Here is a one-liner function based on the function below:

 function IsPalindrome(n) { return n + (((n+="").split("").reverse().join("") == n)? " is a palindrome": " is not a palindrome"); } // ======== test ============= console.log(IsPalindrome(23)); // 23 is not a palindrome console.log(IsPalindrome(121)); // 121 is a palindrome console.log(IsPalindrome(9889)); // 9889 is a palindrome console.log(IsPalindrome(989)); // 989 is a palindrome console.log(IsPalindrome(1)); // 1 is a palindrome

 let a, b = 121; a = b; console.log(String(b).split("").reverse().join() === String(a).split("").join());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM