479. Largest Palindrome Product

Posted __Meng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了479. 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位数的乘积为回文数的数,要求最大

 

C++(496ms):

 1 class Solution {
 2 public:
 3     int largestPalindrome(int n) {
 4         if (n == 1)
 5             return 9 ;
 6         int upper = pow(10 , n) - 1;
 7         int lower = pow(10 , n-1) ;
 8         for(int i = upper ; i >= lower ; i--){
 9             long res = buildPalindrome(i) ;
10             for(long j = upper ; res <= j*j ; j--){
11                 if (res % j == 0 && res / j <= upper)
12                     return res % 1337 ;
13             }
14         }
15         return -1 ;
16     }
17     
18     long buildPalindrome(int num){
19         string s = to_string(num) ;
20         reverse(s.begin() , s.end()) ;
21         return stol(to_string(num) + s) ;
22     }
23 };

 

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

easy479. Largest Palindrome Product

LeetCode 479 - Largest Palindrome Product - Hard ( Python)

479 Largest Palindrome Product 最大回文数乘积

Largest palindrome product

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

Project Euler P4 Largest palindrome product 题解