码迷,mamicode.com
首页 > 其他好文 > 详细

479. Largest Palindrome Product

时间:2018-03-18 21:41:39      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:should   example   UI   upper   public   dig   pre   Plan   color   

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

标签:should   example   UI   upper   public   dig   pre   Plan   color   

原文地址:https://www.cnblogs.com/mengchunchen/p/8597349.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!