leetcode479-Largest-Palindrome-Product

题目要求

Find the largest palindrome made from the product of two n-digit numbers.

Since the result could be very large, you should return the largest palindrome mod 1337.

**Example:**

Input: 2

Output: 987

Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

**Note:**

The range of n is \[1,8\].

函数传入整数n,要求计算出由n位数相乘得出的最大回数时多少。
比如n=2时,由两位数相乘得出的最大回数为9009=99*91,因为可能回数过长,超过int的范围,所以讲结果对1337求余后返回。

思路和代码

这里给出看到的一个解答,就是从大到小获取所有可以构成的回数,并且对n位数从大到小的取余。如果取余的值为0,则代表该回数是最大的回数。

    public int largestPalindrome(int n) {
        if(n == 1) return 9;
        int max = (int)Math.pow(10, n) - 1;
        for(int palindromePart = max - 1 ; palindromePart > max / 10 ; palindromePart--) {
            long palindrome = Long.valueOf(palindromePart + new StringBuilder().append(palindromePart).reverse().toString());
            for(long divided = max ; divided * divided >= palindrome ; divided--) {
                if(palindrome % divided == 0) {
                    return (int) (palindrome % 1337);
                }
            }
        }
        return 0;
    }

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据