Palindrome with length limit

16.09.20201 Min Read — In Algorithms

Question

print all digit formed palindrome within length limit

palindrome(2)
-> [ '11', '22', '33', '44', '55', '66', '77', '88', '99']

Solution

const palindrome = length => {
  const res = []
  const digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

  const add = (current, length) => {
    if (length <= 1) return
    digits.forEach(digit => {
      res.push(digit + current + digit)
      add(digit + current + digit, length - 2)
    })
  }
  digits.forEach(num => {
    add(num, length - 1)
    res.push(num + num)
    add(num + num, length - 2)
  })
  return res.filter(num => !num.startsWith('0'))
}
你必须登录才能发表评论