問題描述:
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==1時,最大的迴文數是9,為奇數,單獨做特殊情況處理;
當n為其他值時,最大的迴文數都是偶數,所以可以利用字串反轉來得到所有的迴文數。
得到迴文數後,需要檢查此迴文數是否可以由兩個數相乘得到(即,使此數依次除以某n位元,看餘數是否為0)。若進行除法運算後,商大於n位元的最大值,則跳出此次迴圈,繼續尋找下一個迴文數。
技巧: 利用StringBuffer類,可以利用reverse()方法直接進行翻轉; 尋找迴文數時,從最大數開始,這樣可以減少時間複雜度。
代碼:
class Solution { public int largestPalindrome(int n) { if(n == 1) return 9; int upper = (int)Math.pow(10,n)-1; for(int i = upper; i>upper/10; i--){ long palin = toPalindrome(i); for(int j = upper; j>upper/10; j--){ if(palin / j > upper) break; if(palin % j == 0) return (int)(palin % 1337); } } return -1; } public long toPalindrome(int i){ StringBuffer str = new StringBuffer(); str.append(i+""); String a = str.reverse().toString(); return Long.parseLong(i+""+a); }}