[LeetCode---Algorithm brushing questions] Number of palindrome (question number: 9)

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

  1. First xconvert the integer to an array
  2. exclude negative numbers
  3. 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:
insert image description here

insert image description here

Problem source: LeetCode
link: https://leetcode-cn.com/problems/palindrome-number/submissions/

Guess you like

Origin blog.csdn.net/honeymoon_/article/details/124405237