Question
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-palindrome-product/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Ideas
1、Answer( Java )
解法思路:回文数构造
⚡️回文数构造算法
// 翻转左半部分到其自身末尾,构造回文数 temp
for (int j = left; j > 0; j /= 10) {
temp = temp * 10 + j % 10;
}
👍根据回文数的特性,只需要枚举左半部分,右半部分即可确定,同时由于两个 n
位整数的乘积至多是个 2n
位数,我们可以从 10^n−1
开始枚举回文数的左半部分。
Code
/**
* @author Listen 1024
* @description 479. 最大回文数乘积(构造回文数)
* @date 2022-04-16 9:13
*/
class Solution {
public int largestPalindrome(int n) {
int res = 0;
if (n == 1) {
return 9;
}
int upper = (int) Math.pow(10, n) - 1;
for (int left = upper; res == 0; --left) {//枚举回文数的左半部分
long temp = left;
for (int j = left; j > 0; j /= 10) {// 翻转左半部分到其自身末尾,构造回文数 temp
temp = temp * 10 + j % 10;
}
for (long k = upper; k * k >= temp; --k) {
if (temp % k == 0) {
res = (int) (temp % 1337);
break;
}
}
}
return res;
}
}
//题解参考链接
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/largest-palindrome-product/solution/zui-da-hui-wen-shu-cheng-ji-by-leetcode-rcihq/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。