Home  >  Article  >  Web Front-end  >  What are palindromes in JavaScript? How to judge?

What are palindromes in JavaScript? How to judge?

青灯夜游
青灯夜游Original
2021-07-02 17:19:233689browse

In JS, a palindrome number refers to an integer that reads the same in forward order (from left to right) and reverse order (from right to left). How to find a palindrome number: first convert the number into an array ; Then use reserve() to reverse the order of the elements in the array; then convert the reversed array into a number; finally use the "===" operator for equality comparison, and if equal, it is a palindrome number.

What are palindromes in JavaScript? How to judge?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Determine whether an integer is a palindrome number. A palindrome number is an integer that reads the same in forward order (from left to right) and reverse order (from right to left).

Example 1:

输入: 121
输出: true

Example 2:

输入: -121
输出: false

Explanation: Reading from left to right, it is -121. Reading from right to left, it is 121- .

So it is not a palindrome number.

Example 3:

输入: 10
输出: false

Explanation: Read from right to left, it is 01.

So it is not a palindrome number.

Problem-solving ideas

The solution I use is string flipping. First convert the test number into a string, because the array has a reserve() method, so Need to convert the string into an array before flipping it

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    // 负数不是一个回文数
    if(x<0){
        return false
    }
    // 对大于0的数进行判断
    else if(x>=0){
        let str = x.toString()  //转化为字符串
        let arr = str.split(&#39;&#39;) //转化为数组
        let res = Number(arr.reverse().join(&#39;&#39;))
        if(x===res){
            return true
        }else if(arr[0]===0){
            return false
        }else if(str!==res){
            return false
        }
    }
};

[Related recommendations: javascript learning tutorial]

The above is the detailed content of What are palindromes in JavaScript? How to judge?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn