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,要求计算出由n位数相乘得出的最大回数时多少。
好比n=2时,由两位数相乘得出的最大回数为9009=99*91,由于可能回数过长,超过int的范围,因此讲结果对1337求余后返回。java
这里给出看到的一个解答,就是从大到小获取全部能够构成的回数,而且对n位数从大到小的取余。若是取余的值为0,则表明该回数是最大的回数。git
public int largestPalindrome(int n) { if(n == 1) return 9; int max = (int)Math.pow(10, n) - 1; for(int palindromePart = max - 1 ; palindromePart > max / 10 ; palindromePart--) { long palindrome = Long.valueOf(palindromePart + new StringBuilder().append(palindromePart).reverse().toString()); for(long divided = max ; divided * divided >= palindrome ; divided--) { if(palindrome % divided == 0) { return (int) (palindrome % 1337); } } } return 0; }