本文主要是介绍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.
示例:
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;}
};
这篇关于Largest Palindrome Product问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!