1. Problem description
Given an integer x, return true if x is a palindromic integer; otherwise, return false.
A palindromic number is an integer that reads the same in forward order (from left to right) and in reverse order (from right to left).
For example, 121 is a palindrome, but 123 is not.
2. Problem-solving ideas
- First
x
convert the integer to an array - exclude negative numbers
- Loop through the array, compare the elements in front of the array with the elements in the back (that is,
0~arr.length - 1,1~(arr.length - 1 - 1),2 ~ (arr.length - 1 - 2)
equal), and continue to loop until the loop reaches the middle element.
3. Problem solving
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
let arr = (x + '').split('');
if(arr[0] === '-') return false;
for(let i = 0; i < arr.length / 2; i++) {
if(arr[i] !== arr[arr.length - 1 - i]) {
return false;
} else {
continue;
}
}
return true;
};
(1) output:
Problem source: LeetCode
link: https://leetcode-cn.com/problems/palindrome-number/submissions/