_leetcode-479
Largest Palindrome Product
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
此题较难,我一开始没读懂题,到现在还是有些没有理解,所以下面是借鉴别人的解法。
此题题意是求两个n位数的最大回文,n是输入,输出有些数太大所以对1337取余。什么是回文?就是数字左右两边对称,比如123321,1221,987789都是回文。
java代码:
public class Solution{
public int largestPalindrome(int n) {
long max = (long)Math.pow(10, n) - 1;
long min = max / 10+1;
for (long h = max; h > min; h--) {
long left = h, right = 0;
for (long i = h; i != 0; i /= 10){
right = right * 10 + i % 10;//9 99 8 89
left*= 10; //990 9900 980 9800
}
long palindrom = left + right; //9999 9889 // construct the palindrome
for (long i = max; i > min; i--) {
long j = palindrom / i;
if (j > i || j <= min) break; // terminate if the other number is greater than current number or is not an n-digit number
if (palindrom % i == 0) return (int)(palindrom % 1337); // found if current number is a factor
}
}
return 9; // account for case n = 1
}
}
浙公网安备 33010602011771号