1.题目
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].
翻译:
找到2个n位数的积,构成的最大回文。因为结果可能会非常大,所以返回mod1337之后的结果。
例如:
输入:2
输出:987
解释:99 x 91 = 9009,9009 % 1337 = 987
提示:
n的范围是[1,8]
2.思路
超时思路:
上界 int high=(int)(Math.pow(10,n))-1 ;下界 int low=(int)(Math.pow(10,n-1));
首先想到的想法就是两层循环,从上界开始向下界递减循环,如果乘积是回文,更新最大乘积。循环全部完成后,返回最大值mod 1337 的结果。然后这个算法到6位数字的时候,发生了超时。
Accepted思路:
上界 int high=(int)(Math.pow(10,n))-1 ;下界 int low=(int)(Math.pow(10,n-1)); 不变。
外层循环 i 从high到low,将i作为前半段构造回文,如 i=9988时,构造pan=99888899; 判断pan是否能由范围内数字相乘得到。
3.算法
①超时算法
public int largestPalindrome(int n) {
if(n==0)return 0;
long res=0;
int high=(int)(Math.pow(10,n))-1;
int low=(int)(Math.pow(10,n-1));
long temp;
for(int i=high;i>=low;i--){
for(int j=i;j>=low;j--){
temp=i*j;
if(isPalindrome(String.valueOf(temp))){
res=res>temp?res:temp;
}
}
}
return (int)(res%1337);
}
public boolean isPalindrome(String nums){
int i=0;
int j=nums.length()-1;
while(i<j){
if(nums.charAt(i)!=nums.charAt(j))
return false;
else{
i++;
j--;
}
}
return true;
}
②Accepted算法
public int largestPalindrome(int n) {
if(n==0)
return 0;
if(n==1)
return 9;
int high=(int)(Math.pow(10,n))-1;
int low=(int)(Math.pow(10,n-1));
for(int i=high;i>low;i--){
long pan=createPalindrome(i);
for(int j=high;j>low;j--){
if(pan/j>high)
break;
if(pan%j==0)
return (int)(pan%1337);
}
}
return -1;
}
long createPalindrome(int num){
String res=String.valueOf(num)+new StringBuilder(String.valueOf(num)).reverse().toString();
return Long.parseLong(res);
}
4.总结
第一个思路是,一直构造乘积,然后判断乘积是否是回文。
新的思路是,先构造回文,然后判断它是否能由两个low-high范围的数相乘得到。
所以想问题可能还是要灵活一些。