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