9.重数(javascript)(9.PalindromeNumber)

原创
小哥 3年前 (2022-11-16) 阅读数 8 #大杂烩

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

示例 1:

输入: 121
输出: true

Example 1:

Input: x = 121
Output: true

示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. 
Therefore it is not a palindrome.

示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Example 4:

Input: x = -101
Output: false

1、x为负数,返回false

2、设置初始值 let temp = true; ,将x转换成字符串,遍历字符串长度的一半
比较字符串前半段和后半段比较,有一个不一样就将 temp = false; ,退出循环

3、最后返回temp的值

例如长度为5
0 -----4 ,,0------5-0-1-----4,,i-------- len - i - 1
1 ------3,,1------5-1-1-----3,,i -------len - i - 1
2-------2,,2------5-2-1-----2,,i------- len - i - 1

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function (x) {
    if (x < 0) {
        return false;
    }
    let temp = true;
    x = x.toString();
    for (let i = 0, len = x.length; i < len / 2; i++) {
         if (x[i] !== x[len - i - 1]) {
             temp = false;
             break
         }
    }
    return temp;
};
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除