1. 程式人生 > >【easy】479. Largest Palindrome Product

【easy】479. Largest Palindrome Product

sin urn example eas put reat amp lan num


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]

/*可以先找到最大的回文數,再檢查能否被分解,如果不能就再找僅次於這個回文數的小回文數:
*/ class Solution { public: int largestPalindrome(int n) { if(n==1) return 9; int upper = pow(10, n) - 1; int lower = pow(10, n - 1); for (int i = upper; i > lower; --i) { long long cand = creatPalindrome(i); for (int j = upper; cand / j < j; --j) {
if (cand % j == 0) return cand % 1337; } } return -1; } private: long long creatPalindrome(int n) { string lastHalf = to_string(n); reverse(lastHalf.begin(), lastHalf.end()); return stoll(to_string(n) + lastHalf); } };

【easy】479. Largest Palindrome Product