'How to solve leetcode problem in JavaScript to check if an integer is a palindrome
Here is the code which i tried to solve, for the leetcode problem in javaScript https://leetcode.com/problems/palindrome-number/ Problem i am facing:
- It is working for even number of digits in an intArr, but not for odd.
let myFunc = (num) => Number(num);
var intArr = Array.from(String(myInt), myFunc);
console.log(intArr.length);
const half = Math.ceil(intArr.length / 2);
const firstHalf = intArr.splice(0, half);
const secondHalf = intArr.splice(-half).reverse();
if (intArr.length % 2 != 0) {
firstHalf.pop();
}
console.log(firstHalf);
console.log(secondHalf);
arrayEquals(firstHalf, secondHalf);
function arrayEquals(firstHalf, secondHalf) {
if (
Array.isArray(firstHalf) &&
Array.isArray(secondHalf) &&
firstHalf.length === secondHalf.length &&
firstHalf.every((val, index) => val === secondHalf[index])
) {
console.log("true");
} else {
console.log("false");
}
}
}
isPalindrome(1221);
isPalindrome(12321);
Please let me know how can i solve this problem. Please correct me if I was wrong in implementing this solution, Thank you.
Solution 1:[1]
You can check weather a number or string is a Palindrome or not by using following Function
const isPalindrome = (input) => {
const arr = (input.toString()).split('');
let isPalindromeInput = true, inputLengthMid = Math.floor(arr.length / 2);
for(let i=0, j=arr.length - 1; i <= inputLengthMid && j >= inputLengthMid; i++, j--) {
if(arr[i].toLowerCase() !== arr[j].toLowerCase()){
isPalindromeInput = false;
break;
}
}
return isPalindromeInput;
}
console.log('isPalindrome : ', isPalindrome('Neveroddoreven'));
console.log('isPalindrome : ', isPalindrome(12321));
console.log('isPalindrome : ', isPalindrome(1221));
console.log('isPalindrome : ', isPalindrome(11214211));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Abdullah Sandral |