[LeetCode] 479. Largest Palindrome Product 最大回文串乘积

 

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

 

这道题给了一个数字n,问两个n位数的乘积组成的最大回文数是多少,返回的结果对 1337 取余。博主刚开始用暴力搜索做,遍历所有的数字组合,求乘积,再来判断是否是回文数,最终超时 TLE 了,只能换一种思路来做。论坛上的这种思路真心叼啊,博主感觉这题绝比不该 Easy 啊。首先还是要确定出n位数的范围,最大值 upper,可以取到,最小值 lower,不能取到。然后遍历这区间的所有数字,对于每个遍历到的数字,用当前数字当作回文数的前半段,将其翻转一下拼接到后面,此时组成一个回文数,这里用到了一个规律,当 n>1 时,两个n位数乘积的最大回文数一定是 2n 位的。下面就要来验证这个回文数能否由两个n位数相乘得来,还是遍历区间中的数,从 upper 开始遍历,但此时结束位置不是 lower,而是当前数的平方大于回文数,因为遍历的是相乘得到回文数的两个数中的较大数,一旦超过这个范围,就变成较小数了,就重复计算了。比如对于回文数 9009,其是由 99 和 91 组成的,其较大数的范围是 [99,95],所以当遍历到 94 时,另一个数至少需要是 95,而这种情况在之前已经验证过了。当回文数能整除较大数时,说明是成立的,直接对 1337 取余返回即可,参见代码如下:

 

class Solution {
public:
    int largestPalindrome(int n) {
        int upper = pow(10, n) - 1, lower = upper / 10;
        for (int i = upper; i > lower; --i) {
            string t = to_string(i);
            long p = stol(t + string(t.rbegin(), t.rend()));
            for (long j = upper; j * j > p; --j) {
                if (p % j == 0) return p % 1337;
            }
        }
        return 9;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/479

 

参考资料:

https://leetcode.com/problems/largest-palindrome-product/

https://leetcode.com/problems/largest-palindrome-product/discuss/96291/an-easy-9-line-java-solution

https://leetcode.com/problems/largest-palindrome-product/discuss/96297/Java-Solution-using-assumed-max-palindrom

https://leetcode.com/problems/largest-palindrome-product/discuss/96306/Java-solutions-with-two-different-approaches

 

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2017-10-10 11:32  Grandyang  阅读(4843)  评论(1编辑  收藏  举报
Fork me on GitHub