LeetCode-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.

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值