题目:
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位数相乘得到的最大的回文数。
因为得到的结果可能会很大,你需要返回最大的回文数模1337得到的余数。
例子:
输入:2
输出:987
解释:99 x 91 = 9009, 9009 % 1337 = 987
注意:
n的范围为[1,8]
思路:
简单来说,从最大的n位数开始找,最大的n位数和这个最大n位数的翻转拼接起来一定是一个回文数,例如90 和09 拼接后得到9009,是个回文数,但是这个回文数是否可以整除这个最大的n位数呢,若是能够整除,那么这个拼接起来的数字就是我们要找的最大回文数了。
C++代码(Visual Studio 2017):
#include "stdafx.h" #include <iostream> #include <string> using namespace std; class Solution { public: int largestPalindrome(int n) { int upper = pow(10, n) - 1; int lower = upper / 10; for (int i = upper; i > lower; i--) { string l = to_string(i); long t = stol(l + string(l.rbegin(), l.rend())); for (long s = upper; s * s > t; s--) { if (t % s == 0) return t % 1337; } } return 9; } }; int main() { Solution s; int n = 2; int result; result = s.largestPalindrome(n); cout << result; return 0; }