479. Largest Palindrome Product
Description
Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.
Example 1:
Input: n = 2 Output: 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
Example 2:
Input: n = 1 Output: 9
Constraints:
1 <= n <= 8
Solutions
Solution 1
Thinking
The largest palindrome that is a product of two \(n\)-digit integers, modulo \(1337\). \(n\le 8\), so listing every product is heavy.
Enumerate the first half \(a\) downward, mirror it to a palindrome \(x\), and test for an \(n\)-digit factor \(t\) (from \(10^n-1\) down while \(t^2\ge x\)). The first hit is the maximum.
Building palindromes first meets the largest candidates sooner than enumerating products. \(n=1\) falls through to \(9\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |