首页 > 其他分享 >1~10000之间的所有对称数

1~10000之间的所有对称数

时间:2023-01-27 16:23:03浏览次数:50  
标签:10 arr 10000 所有 rev num let 对称 const

  数组反转

const findPalindromeByReserveArray = () => {
    const arr = []
    for(let i = 1; i <= 10000; i++){
        const str = String(i)
        const strArr = str.split('')
        if(str === strArr.reverse().join('')){
            arr.push(i)
        }
    }
    return arr
}

  字符串前后index值比较

const findPalindromeByCompareIndex = () => {
    const arr = []
    for(let i = 1; i <= 10000; i++){
        const s = String(i)
        const length = s.length
        let startIndex = 0
        let endIndex = length - 1
        let flag = true
        while(startIndex < endIndex){
            if(s[startIndex] === s[endIndex]){
                startIndex++
                endIndex--
            }else{
                flag = false
                break
            }
        }
        if(flag) arr.push(i)
    }
    return arr
}

  翻转数字方法

const reverseNumbers = (num) => {
    let rev = 0
    while(num > 0){
        rev = rev * 10 + num % 10
        num = Math.floor(num / 10)
    }
    return rev
}

  使用翻转数字

const findPalindromeByCreateReverseNumbers = () => {
    const arr = []
    for(let i = 1; i <= 10000; i++){
        let rev = reverseNumbers(i)
        if(i === rev) arr.push(i)
    }
    return arr
}

  

标签:10,arr,10000,所有,rev,num,let,对称,const
From: https://www.cnblogs.com/zhenjianyu/p/17068941.html

相关文章