[LeetCode/LintCode] Largest Palindrome Product

linspiration發表於2019-01-19

Problem

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

Solution

public class Solution {
    /**
     * @param n: the number of digit
     * @return: the largest palindrome mod 1337
     */
    public int largestPalindrome(int n) {
        // when n == 1, largest palindrome would be single-digit
        if (n == 1) return 9;
        
        // get the maximum and the minimum factors
        long maxFactor = (long)Math.pow(10, n)-1;
        long minFactor = (long)Math.pow(10, n-1);
        
        // get the largest product first, then use the first half to create palindrome
        long maxProduct = (long)maxFactor * (long)maxFactor;
        long maxHalf = maxProduct / (long)Math.pow(10, n);

        // initialize result palindrome to 0, and set the flag to check if result found and end the while loop
        long palindrome = 0;
        boolean palindromeFound = false;
        
        while (!palindromeFound) {
            // generate the latest largest palindrome in each cycle
            palindrome = generatePalindrome(maxHalf);
            
            for (long i = maxFactor; i >= minFactor; i--) {
                // the generated palindrome cannot be larger than maxFactor * maxFactor
                if (palindrome / i > i || palindrome / maxFactor > maxFactor) {
                    break;
                }
                
                if (palindrome % i == 0) {
                    palindromeFound = true;
                    break;
                }
            }
            //when for loop ends, decrease maxHalf by 1 to generate the next palindrome
            maxHalf--;
        }
        
        return (int)(palindrome % 1337);
    }
    
    public long generatePalindrome(long num) {
        String str = String.valueOf(num) + new StringBuilder().append(num).reverse().toString();
        return Long.parseLong(str);
    }
}

相關文章