0479. Largest Palindrome Product

https://leetcode.com/problems/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

ac

class Solution {
    public int largestPalindrome(int n) {
        // edge cases
        if (n <= 0) return 0;
        if (n == 1) return 9;

        int maxNum = (int) Math.pow(10, n) - 1; // 100 - 1 = 99
        int minNum = (int) Math.pow(10, n-1);  // 10

        // iterate from maxNum -> minNum
        for (int i = maxNum; i >= minNum; i--) {
            // construct palindromic number
            long palindromicNum = Long.parseLong(i + new StringBuilder().append(i).reverse().toString()); // 98 + 89 -> 9889

            // check from max to min, if can be divided, get result
            for (long f1 = maxNum; f1 * f1 >= palindromicNum; f1--) {
                // long f2 = palindromicNum / f1;
                // if (f2 > maxNum || f2 < minNum) break;

                if (palindromicNum % f1 == 0) return (int)(palindromicNum % 1337);
            }
        }

        return 0;
    }
}

Last updated