479. Product of Maximum Palindromic Numbers: Enumeration Problems

Get into the habit of writing together! This is the 16th day of my participation in the "Nuggets Daily New Plan·April Update Challenge", click to view the event details .

Topic description

This is 479. Maximum Palindromic Product on LeetCode on Hard difficulty .

Tag : "enumeration", "math"

given an integer n n , the return can be expressed as two n n  -bit integers.

Because the answer can be very large, return it for 1337 1337 Extra.

Example 1:

输入:n = 2

输出:987

解释:99 x 91 = 9009, 9009 % 1337 = 987
复制代码

Example 2:

输入: n = 1

输出: 9
复制代码

hint:

  • 1 < = n < = 8 1 <= n <= 8

Enumeration + Math

for digits n n , the number of digits in the product is either 2 n 2 * n , either 2 n 1 2 * n - 1

when digital n > 1 n > 1 , we can always 2 n 2 * n .

Using the characteristics of the palindrome, we only need to enumerate the first half of the palindrome (the second half is uniquely determined), and we only need to follow the "large to small" when enumerating the first half to ensure that the found The first legal value is the largest number, and for a digit is n n The maximum number of 1 0 n 1 10^n - 1

具体的,当枚举到回文串的前半部分 i i 时,我们利用回文串特性构造出具实际的回文数值 n u m s nums ,随后检查 n u m s nums 能否分解成数位为 n n 的数对 ( a , b ) (a, b) ,利用乘法具有交换律,我们只需要枚举数对中的较大数即可。

代码:

class Solution {
    public int largestPalindrome(int n) {
        if (n == 1) return 9;
        int max = (int) Math.pow(10, n) - 1;
        for (int i = max; i >= 0; i--) {
            long num = i, t = i;
            while (t != 0) {
                num = num * 10 + (t % 10);
                t /= 10;
            }
            for (long j = max; j * j >= num; j--) {
                if (num % j == 0) return (int)(num % 1337);
            }
        }
        return -1;
    }
}
复制代码
  • 时间复杂度:枚举回文串的前半部分复杂度为 O ( 1 0 n ) O(10^n) ;检查回文串能否被分解复杂度为 O ( 1 0 n ) O(10^n) 。整体复杂度为 O ( 1 0 2 n ) O(10^{2n})
  • 空间复杂度: O ( 1 ) O(1)

最后

This is the first No.479article series starts on 2021/01/01. As of the starting date, there are 1916 questions on LeetCode, some of which are locked. We will first put all the questions without locks. Topic finished.

In this series of articles, in addition to explaining the problem-solving ideas, the most concise code will be given as much as possible. If general solutions are involved, corresponding code templates will also be provided.

In order to facilitate students to debug and submit code on the computer, I have established a related repository: github.com/SharingSour… .

In the warehouse address, you can see the link to the solution of the series of articles, the corresponding code of the series of articles, the link to the original question of LeetCode and other preferred solutions.

Guess you like

Origin juejin.im/post/7087026602332127246