Leetcode 479. Largest palindrome product Max Palindrome product __leetcode

Source: Internet
Author: User

Problem Description:

Find the largest palindrome made from the product of two n-digit numbers.
Since The result could is 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].

Ideas for solving problems:

When N==1, the biggest palindrome number is 9, for odd-numbered, do special case processing alone;
When n is another value, the largest palindrome number is even, so you can use string Park to get all the palindrome numbers.

After the number of palindrome, you need to check whether this palindrome can be multiplied by two numbers (that is, so that the number divided by a number of n digits, see whether the remainder is 0). If the division operation, the quotient is greater than n digits of the maximum value, then jump out of this cycle, continue to find the next palindrome number.

Tip: Use the StringBuffer class, you can use the reverse () method to flip directly, looking for palindrome number, starting from the maximum number, this can reduce the time complexity.

Code:

class Solution {public int largestpalindrome (int n) {if (n = 1) return
        9;
        int upper = (int) Math.pow (10,n)-1;
            for (int i = upper; i>upper/10; i--) {Long Palin = topalindrome (i);
                for (int j = Upper; j>upper/10; j--) {if (palin/j > Upper) break;
            If (palin% J = = 0) return (int) (palin% 1337);        
    }} return-1;
        public long topalindrome (int i) {stringbuffer str = new StringBuffer ();
        Str.append (i+ "");
        String a = Str.reverse (). toString ();
    Return Long.parselong (i+ "" +a); }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.