[LeetCode] Largest Palindrome Product

479. Largest Palindrome Product

Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
long long mod = 1337;
long long palindrome(long long n) {
string rev = to_string(n);
reverse(begin(rev), end(rev));
return stoll(to_string(n) + rev);
}
public:
int largestPalindrome(int n) {
if(n == 1) return 9;
long long ma = pow(10,n) - 1, mi = ma / 10;
for(long long i = ma; i > mi; i--) {
long long pal = palindrome(i);
for(long long j = ma; j * j >= pal; j--) {
if(pal % j == 0 and pal / j <= ma) return pal % mod;
}
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/22/PS/LeetCode/largest-palindrome-product/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.