Use two methods to solve the "maximum palindromic product" problem

14. Product of maximum palindrome numbers

14.1. Requirements for the title

Given an integer n, return the largest palindrome integer that can be represented as the product of two n-bit integers. Because the answer can be very large, it is returned in the remainder of 1337.

示例 1:
输入:n = 2
输出:987
解释:99 x 91 = 9009, 9009 % 1337 = 987

示例 2:
输入: n = 1
输出: 9

提示:
1 <= n <= 8

Source: LeetCode
Link: https://leetcode-cn.com/problems/largest-palindrome-product

14.2. Problem solving ideas

The first solution:

First calculate the maximum product, then take out the first half of the number of the maximum product and use the generator function to generate the corresponding palindrome number, then compare the generated palindrome numbers, if not found, decrement the first half of the number and regenerate it The new palindrome numbers are compared, and the loop goes on in turn; if they are found, they can be output.

Second solution:

Because the scope of this question is fixed and relatively small, you can directly type the table.

14.3. Algorithms

The first algorithm:

class Solution {
    
    
    public int largestPalindrome(int n) {
    
    
        //如果n为1,则只有9最大
        if (n == 1) {
    
    
            return 9;
        }
        //定界限
        long upper = (long) Math.pow(10,n) - 1;
        long lower = upper/10 + 1;
        //范围中的最大乘积
        long maxNumber = upper * upper;
        //计算最大数字的前半部分
        long half = (long) (maxNumber/Math.pow(10,n));
        //是否找到
        boolean found = false;
        //返回值
        long result = 0;
        //循环找对应的回文数
        while (!found){
    
    
            //调用生成函数
            result = create(half);
            //从高往低进行查找
            for (long i = upper; i >= lower; i--) {
    
    
                //i*i的值小于result的值
                if (i * i < result){
    
    
                    break;
                }
                //result对i取余为0
                if (result % i == 0){
    
    
                    found = true;
                    break;
                }
            }
            //没找到,接着找前半部分下一位数字
            half--;
        }
        //返回回文数并对1337取余
        return (int) (result % 1337);
    }

    //生成函数
    public long create(long number){
    
    
        //将传来的数字前半部分与翻转生成的前半部分的数字拼接生成新的回文数
        String str = number + new StringBuilder().append(number).reverse().toString();
        return Long.parseLong(str);
    }
}

Reference video: Guo Guo, the master of Likouup

Second algorithm:

class Solution {
    
    
    public int largestPalindrome(int n) {
    
    
        int[] palindromes = {
    
    9,987,123,597,677,1218,877,475};
        return palindromes[n - 1];
    }
}

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124209836