E.Moon
E.Moon

Reputation: 5

Number palindromes code not working

Ive been doing the 'Numerical Palindrome #1' Kata in codewars and I feel like this code should work, but its saying that palindrome(1221) is coming back as false - when obviously it should be coming back as true. if anyone can see why this would be happening i would greatly appreciate it! the challenge said that if num was less than 0, or wasnt an integer then it should return 'not valid'.

    function palindrome(num) { 

    if(typeof num == 'number'){

        if(Number.isInteger(num) && num>=0){
              return(toString(num) === toString(num).split('').reverse().join(''));
              }
        else{return 'Not valid';
        }
        }
    else { return 'Not valid';
    }
   }

Upvotes: 0

Views: 78

Answers (4)

bonev93
bonev93

Reputation: 13

You should use String instead of toString.

function palindrome(num) { 
    if (typeof num == 'number' && Number.isInteger(num) && num >= 0) {
        return (String(num) === String(num).split('').reverse().join(''));
    }
    return 'Not valid';

}

Upvotes: 0

Emad Dehnavi
Emad Dehnavi

Reputation: 3451

There was some problem with your code. you need to use toString() like below :

num.toString()

and also you don't need two if for checking your conditions, you can do it with only 1 if.

I update your code :

var a =  function palindrome(num) { 
    if(typeof num == 'number' && Number.isInteger(num) && num>=0)       
          return(num.toString() === num.toString().split('').reverse().join(''));                 
    else 
          return 'Not valid';    
}   
console.log(a(1001));

https://jsfiddle.net/emilvr/qkz5ypq9/

Upvotes: 1

Gautam
Gautam

Reputation: 825

toString method that you are using will return toString(123456) = "[object Undefined]" . & toString(123456).split('').reverse().join('') = "]denifednU tcejbo[" and hence it is failing. to convert a number to string best is to concatenate it with "", like 12345+"";

Upvotes: 0

Emil S. Jørgensen
Emil S. Jørgensen

Reputation: 6366

toString is a method of Number.prototype so you call it from the number:

function palindrome(num) {

  if (typeof num == 'number') {

    if (Number.isInteger(num) && num >= 0) {
      return (num.toString() === num.toString().split('').reverse().join(''));
    } else {
      return 'Not valid';
    }
  } else {
    return 'Not valid';
  }
}

console.log(palindrome(500))
console.log(palindrome(505))

Upvotes: 2

Related Questions