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