Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function that checks whether number is palindrome

Tags:

javascript

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!

like image 346
Jenny Avatar asked Aug 07 '26 20:08

Jenny


1 Answers

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";
like image 125
David Avatar answered Aug 09 '26 13:08

David