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 = 3,则我们由大到小,列出可能的对称数t,t为998899,997799,.......,101101,100001...,当然,后面还会有一些比100001更小的对称数,但如果100001前面这些数能满足条件的话,即可返回。
再将t分解为两个数相乘,因此,只要找到sqrt(t)前面部分的数能否被t相除即可,如果能,说明当前的t即为所求。
如果都没有,则说明对称的数可能位于10000~100000之间(0~10000之间是n=2所求,可以过滤掉)。
本题恰好能在100001~9998899之间能找到对称的数,本人无法证明,希望明白人能够指点。
class Solution {
public int largestPalindrome(int n) {
if (n == 1){
return 9;
}
int m = (int)Math.pow(10, n) - 1, t = m/10;
for (int i = m-1; i > t; -- i){
long val = Long.parseLong(i + new StringBuilder(i+"").reverse().toString());
for (int j = m; j >= (int)Math.sqrt(val); -- j){
if ((val % j) == 0){
return (int)(val%1337);
}
}
}
return 0;
}
}