[LeetCode] Largest Palindrome Product
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位数相乘。最后将符合条件的回文数整除。
class Solution { public: int largestPalindrome(int n) { if (n == 1) return 9; long maxVal = pow(10, n) - 1; long minVal = maxVal / 10; for (long i = maxVal; i >= minVal; i--) { long val = createPalindrome(i); for (int j = maxVal; j >= minVal; j--) { if (val / j > maxVal) { break; } if (val % j == 0) { return static_cast<int>(val % 1337); } } } return 0; } long createPalindrome(long num) { long tmp = num; long a = 0; int n = 0; while(tmp) { a = a * 10 + tmp % 10; n++; tmp /= 10; } while(n) { num = num *10; n--; } return num + a; } }; // 1354 ms
Trick algorithm:
class Solution { public: int largestPalindrome(int n) { vector<long> pattern{9, 9009, 906609, 99000099, 9966006699, 999000000999, 99956644665999, 9999000000009999}; return static_cast<int>(pattern[n - 1] % 1337); } }; // 0 ms