题目要求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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求余后返回。
思路和代码
这里给出看到的一个解答,就是从大到小获取所有可以构成的回数,并且对n位数从大到小的取余。如果取余的值为0,则代表该回数是最大的回数。
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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; }
|