This is the seventh day of my participation in the August More text Challenge. For details, see: August More Text Challenge


Palindrome is a magic, it embodies a kind of symmetry, everywhere in the nature are examples of symmetry, the limbs of cheetah, the lion’s face, a beautiful butterfly wings, and so on, from the ancient, before our buildings are mostly symmetrical, like the tiananmen square, even the entire palace built of symmetry, below to see how palindrome judgment.

Topic describes

Given an integer x, return true if x is a palindrome; Otherwise, return false.

Palindromes are integers that are read in the same order (from left to right) and in the same order (from right to left). For example, 121 is a palindrome, while 123 is not.


Example 1:

Enter: x = 121

Output: true,

Example 2:

Enter: x = -121

Output: false

Explanation: Read from left to right, it is -121. Read from right to left: 121-. So it’s not a palindrome number. Example 3:

Enter: x = 10

Output: false

Explanation: read from right to left, as 01. So it’s not a palindrome number.

Example 4:

Enter: x = -101

Output: false


-231 <= x <= 231 – 1


  • If the value is negative, return false. If the value is false, return false
  • So the idea here is that we’re going to reverse the input by taking the mod and the quotient, and then we’re going to compare what we get with what we get. The following code
var isPalindrome = function(x) {
    if(x < 0)
        return false;
    var cur = 0;
    var num = x;
    while(num ! =0) {
        cur = cur * 10 + num % 10; 
        num= parseInt(num/10)}return cur === x;
Copy the code

The running result of LeetCode is as follows


  • We can solve the problem in a different way, we can treat the input as a string, first calculate the length of the converted string /2 forensics, and then do different operations by taking mod equals zero
  • If the range is equal to 0, the number of strings is even, then right=left+1, otherwise right=left+2
  • X [left]===x[right] == false; otherwise left–, right++, return true
/ * * *@param {number} x
 * @return {boolean}* /
var isPalindrome = function(x) {
    var left =parseInt(x.length/2) -1
    var right
    if(x.length%2= = =0){
    while(left>=0&&right<=x.length-1) {if(x[left]===x[right]){
            return false}}return true
Copy the code

The running result of LeetCode is as follows:


Either way, the problem can be solved, but the time and memory required to solve the problem are different, as is evident from the above diagram.

You are welcome to share better solutions