JS Likou classic 100 questions - palindrome number

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.

Example 1:

Input: x = 121
Output: true

Example 2:

Input: x = -121
Output: false
Explanation: Read from left to right, it is -121. Read from right to left, it is 121-. Therefore it is not a palindromic number.

Example 3:

Input: x = 10
Output: false
Explanation: Read from right to left, it is 01. Therefore it is not a palindromic number.

hint:

    -231 <= x <= 231 - 1

Advanced: Can you solve this without converting the integer to a string? cannot

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
   let str = x.toString()
   let mid = Math.floor(str.length/2)
   let flag = str.length%2
   let left,right
   if(flag){
        left = mid-1
        right = mid +1
   } else {
        left = mid-1
        right = mid
   }
   while(left>=0 && right<str.length){
       if(str.charAt(left) != str.charAt(right)){
           return false
       } else {
           left--
           right++
       }
   }
   return true
};

Guess you like

Origin blog.csdn.net/qq_36384657/article/details/128212247