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 e up with a working solution. Thanks for reading or even helping me out!
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 e up with a working solution. Thanks for reading or even helping me out!
Share Improve this question asked Jul 2, 2020 at 13:45 JennyJenny 4941 gold badge6 silver badges18 bronze badges 4-
i<numToStringArray;
-numToStringArray
is an array of strings (characters). You want its.length
– Andreas Commented Jul 2, 2020 at 13:49 -
return
stops the execution of the function, you might want to think about that too. – Andreas Commented Jul 2, 2020 at 13:50 -
Even after fixing the loop test, there is another logical error. You want the positive return only after you've checked for all the possible negative ones. If you remove
return "It's a palindrome"
from theelse
clause and put it after the loop has finished, it should work. But as other answers show, there are better ways of writing this code. – Scott Sauyet Commented Jul 2, 2020 at 14:18 - Also note that there is a very strong convention in JS that function names are only capitalized if they're constructor functions. – Scott Sauyet Commented Jul 2, 2020 at 14:24
11 Answers
Reset to default 2I'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 pletes 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 ments.
The simplest way to achieve what you want though, would simply be-
function isPalindrome(num) {
return num === Number(num.toString().split('').reverse().join(''));
}
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
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 pare them, like this:
function Palindrome(num) {
let numToStringArray = num.toString().split('');
let reversedArray = numToStringArray.reverse().join('');
if (num.toString() == reversedArray)
console.log('It\'s a palindrome');
else
console.log('It\'s not a palindrome');
}
Palindrome(9);
Palindrome(232);
Palindrome(152);
let a, b = 121;
a = b;
console.log(String(b).split("").reverse().join() === String(a).split("").join());