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 };

 

posted @ 2018-03-18 20:43  __Meng  阅读(108)  评论(0编辑  收藏  举报