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;
}
};
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;
}
};
相关文章推荐
- projecteuler网站第四题解法:Find the largest palindrome made from the product of two 3-digit numbers
- Project Euler 004 Largest palindrome product
- Problem 4:Largest palindrome product
- 欧拉计划之Largest palindrome product
- Project Euler Problem 4: Largest palindrome product
- [LeetCode] Largest Palindrome Product 最大回文串乘积
- (Problem 4)Largest palindrome product
- 479. Largest Palindrome Product
- (Problem 4)Largest palindrome product
- Project Euler 4 Largest palindrome product
- Valid Palindrome II问题及解法
- projecteuler---->problem=4----Largest palindrome product
- Largest palindrome product——查找最大回文数
- 【欧拉计划4】Largest palindrome product
- leetcode[Largest Palindrome Product]
- Maximum Product of Word Lengths 问题及解法
- Largest Divisible Subset问题及解法
- 【欧拉计划4】Largest palindrome product
- Proiect Euler problem 4 : Largest palindrome product
- 479. Largest Palindrome Product