easy479. Largest Palindrome Product

Posted Sherry_Yang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了easy479. 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]

/*可以先找到最大的回文数,再检查能否被分解,如果不能就再找仅次于这个回文数的小回文数:*/
class Solution {
public:
    int largestPalindrome(int n) {
        if(n==1) return 9;
        int upper = pow(10, n) - 1;
        int lower = pow(10, n - 1);
        for (int i = upper; i > lower; --i) {
            long long cand = creatPalindrome(i);
            for (int j = upper; cand / j < j; --j) {
                if (cand % j == 0) return cand % 1337;
            }
        }
        return -1;
    }

private:
    long long creatPalindrome(int n) {
        string lastHalf = to_string(n);
        reverse(lastHalf.begin(), lastHalf.end());
        return stoll(to_string(n) + lastHalf);
    }
};

 

以上是关于easy479. Largest Palindrome Product的主要内容,如果未能解决你的问题,请参考以下文章

479. Largest Palindrome Product

LeetCode 479 - Largest Palindrome Product - Hard ( Python)

479 Largest Palindrome Product 最大回文数乘积

Leetcode_easy976. Largest Perimeter Triangle

[LeetCode] 812. Largest Triangle Area_Easy tag: math

[LeetCode] 747. Largest Number At Least Twice of Others_Easy