您的位置:首页 > 其它

Largest Palindrome Product问题及解法

2017-08-18 11:25 435 查看
问题描述:

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.
示例:
Input: 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

Note:
The range of n is [1,8].
问题分析:
求出n为整数的最大值,从最大依次到最小构造回文数,对于构造出的回文数,进行判断是否是两个n位数相乘的积。

过程详见代码:
class Solution {
public:
int largestPalindrome(int n) {
if (n == 1) return 9;
int max = pow(10, n) - 1;
for (int v = max - 1; v > max / 10; v--)
{
string s = to_string(v);
reverse(s.begin(), s.end());
s = to_string(v) + s;
long long u = stol(s);
for (long long x = max; x*x >= u; x--)
if (u%x == 0)
return (int)(u % 1337);
}
return 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: