Skip to content

Latest commit

 

History

History
44 lines (37 loc) · 1014 Bytes

479.最大回文数乘积.md

File metadata and controls

44 lines (37 loc) · 1014 Bytes

479.最大回文数乘积

/*
 * @lc app=leetcode.cn id=479 lang=typescript
 *
 * [479] 最大回文数乘积
 */

// @lc code=start
function largestPalindrome(n: number): number {}
// @lc code=end

解法 1: 枚举

function largestPalindrome(n: number): number {
  if (n === 1) return 9
  const MOD = BigInt(1337)
  const max = BigInt(10 ** n - 1),
    min = BigInt(10 ** (n - 1))
  for (let i = BigInt(max); ; i--) {
    const num = BigInt(i.toString() + i.toString().split('').reverse().join(''))
    for (let j = max; j * j >= num; j--) {
      if (num % j === 0n && num / j > min) return Number(num % MOD)
    }
  }
}

Case

test.each([
  { input: { n: 2 }, output: 987 },
  { input: { n: 1 }, output: 9 },
  { input: { n: 8 }, output: 475 },
])('input: n = $input.n', ({ input: { n }, output }) => {
  expect(largestPalindrome(n)).toEqual(output)
})