LeetCode Largest Palindrome Product

原题链接在这里:https://leetcode.com/problems/largest-palindrome-product/description/

题目:

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=2时,数字可选区间就是(9, 99]. 最大的product 就是 99*99 = 9801. 最大的位数是2n 肯定是个偶数. 

取前一半firstHalf '98', 再拼接'98'的reverse '89'组成新的palindrome '9889'. 然后i在(9,99]之间挨个试palindrome % i == 0.

试不出来firstHalf--, 变'97'重来.

Time Complexity: O((upperBound*upperBound)/10^n  * (upperBound*lowerBound)), upperBound = 10^n, lowerBound = upperBound/10.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int largestPalindrome(int n) {
 3         if(n == 1){
 4             return 9;
 5         }
 6         
 7         int upperBound = (int)Math.pow(10, n) - 1;
 8         int lowerBound = upperBound/10;
 9         long max = (long)upperBound * (long)upperBound;
10         
11         int firstHalf = (int)(max/(long)Math.pow(10,n));
12         boolean palFound = false;
13         long pal = 0;
14         while(!palFound){
15             pal = createPal(firstHalf);
16             
17             for(long i = upperBound;; i--){
18                 if(pal/i>max || i*i<pal){
19                     break;
20                 }
21                 if(pal%i == 0){
22                     palFound = true;
23                     break;
24                 }
25             }
26             
27             firstHalf--;
28         }
29         return (int)(pal%1337);
30     }
31     
32     private long createPal(int n){
33         String s = n + new StringBuilder().append(n).reverse().toString();
34         return Long.valueOf(s);
35     }
36 }

 

posted @ 2017-09-19 13:43  Dylan_Java_NYC  阅读(473)  评论(0编辑  收藏  举报