1. 程式人生 > >479. Largest Palindrome Product

479. Largest Palindrome Product

pro 鏡面反射 AD result you TP could out 回文

問題描述:

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].

解題思路:

沒有思路,參考了GrandYang的解法

先找n個數字能夠組成的最大值upper和最小值lower

最大的值的長度應為2n

我們可以從上界upper將其做鏡面反射構成一個回文然後檢查是否存在兩個值可以得到這樣的乘積。

代碼:

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

479. Largest Palindrome Product