1~10000之间的所有对称数

  数组反转
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 findPalindrome = (n = 10000) => {
    const reserveNumber = (num) => {
        let base = 0
        while (num > 0) {
            base = base * 10 + num % 10
            num = Math.floor(num / 10)
        }
        return base
    }
    const res = []
    while (n > 0) {
        if (reserveNumber(n) === n) res.push(n)
        n--
    }
    return res
}

 

const isReserveNum = (num = 1234321) => {
  const s = String(num);
  for (let i = 0; i < s.length; i++) {
    const v = s[i];
    if (v !== s[s.length - 1 - i]) return false;
  }
  return true;
};

  

 

  

posted @ 2023-01-27 16:12  671_MrSix  阅读(139)  评论(0编辑  收藏  举报