This code is working fine except any number which is multiples of 10s. I tested with 121, -121, 55, -55. It was executing fine. but with 10 it's not generating the right answer.
var isPalindrome = function(x) {
var convertToString= toString(x);
var splitString= convertToString.split("");
var reversedString= splitString.reverse();
if(x<0){
return false;
}
if(reversedString == splitString){
return true;
} else {
return false;
}
};
CodePudding user response:
The implementation of your function is totally wrong. It shouldn't work with any given input.
if(convertToString == splitString) // comparison
here you are using comparison operator to compare both values, but underneath the hood the compiler is comparing [ ] = [ ] the values inside the arrays doesn't matter it will always be true. you have to find a way to compare the values inside both of the arrays to get the function to work. (Spoiler : you could use some kind of loop to compare the values)
And use the toString function like this,
var convertToString= x.toString();
to get stringified value of x.
CodePudding user response:
There are a couple problems with this code, although you're on the right track. First, your usage of toString
is slightly wrong:
toString(101); // '[object Undefined]'
toString
should be called as a method of x
, like x.toString()
. See this page for more details. If you change it to x.toString()
, it works:
var x = 101; // "101"
Second, you are currently comparing arrays with ==
, which won't do what you want. Notice that:
[0, 1] == [0, 1] // false
whereas
"01" == "01" // true
This is because JS compares strings by value, but doesn't compare objects (which includes arrays) by value. For example:
var x = 1;
var y = 1;
console.log(x == y); // true
var a = [1];
var b = [1];
console.log(a == b); // false
console.log(a == a); // true
To learn more about this, read this question or try googling for 'javascript pass by reference'. But in brief, one solution to your problem would be to just use strings, which work as you would expect with ==
.
After fixing these problems, your code should look like this:
var isPalindrome = function(x) {
var convertToString= String(x);
var reversedString= convertToString.split("").reverse().join("");
if(x<0){
return false;
}
if(convertToString == reversedString){
return true;
} else {
return false;
}
};
You could also consider shortening the if statement at the end and making the spacing more consistent:
var isPalindrome = function(x) {
var convertToString = String(x);
var reversedString = convertToString.split("").reverse().join("");
if(x < 0){
return false;
}
return convertToString == reversedString;
};