479.最大回文数乘积

题目

479.最大回文数乘积

题目大意

给定一个整数 n ,返回 可表示为两个 n 位整数乘积的 最大回文整数 。因为答案可能非常大,所以返回它对 1337 取余

样例

示例 1:

输入:n = 2
输出:987
解释:99 x 91 = 9009, 9009 % 1337 = 987

示例 2:

输入: n = 1
输出: 9

数据规模

提示:

  • 1 <= n <= 8

思路

考虑枚举,从大到小枚举回文数,但是考虑到它是一个回文数,那么就只需要枚举回文数的左半部分,其右半部分也就确定了。同时由于两个 n n n位整数的乘积至多是个 2 n 2n 2n位数,可以从 1 0 n − 1 10^n-1 10n1 开始枚举回文数的左半部分。

1 0 n − 1 10^n-1 10n1开始从大到小枚举 l l l,根据 l l l可以得到 r r r,从而得到回文数 t t t

得到回文数 t t t后,需要判断其能否分解成两个 n n n位整数。可以从 1 0 n − 1 10^n-1 10n1开始从大到小枚举 i i i,若 i i i能整除 t t t i i i t i \frac{t}{i} it n n n位整数,则 t t t就是我们要找的答案。

代码

// short int long float double bool char string void
// array vector stack queue auto const operator
// class public private static friend extern 
// sizeof new delete return cout cin memset malloc
// relloc size length memset malloc relloc size length
// for while if else switch case continue break system
// endl reverse sort swap substr begin end iterator
// namespace include define NULL nullptr exit equals 
// index col row arr err left right ans res vec que sta
// state flag ch str max min default charray std
// maxn minn INT_MAX INT_MIN push_back insert
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int>PII;
typedef pair<int, string>PIS;
const int maxn=1e6+50;//注意修改大小
long long read(){long long x=0,f=1;char c=getchar();while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}while(isdigit(c)){x=x*10+c-'0';c=getchar();}return x*f;}
ll qpow(ll x,ll q,ll Mod){ll ans=1;while(q){if(q&1)ans=ans*x%Mod;q>>=1;x=(x*x)%Mod;}return ans%Mod;}

class Solution {
public:
    int largestPalindrome(int n) {
        if(n==1)return 9;
        ll upper=qpow(10,n,1000000000000)-1;
        for(ll l=upper;l;l--){
            ll t=l;
            ll r=l;
            while(r){
                t=t*10+r%10;
                r/=10;
            }
            for(ll i=upper;i*i>=t;i--){
                if(t%i==0){
                    return t%1337;
                }
            }
        }
        return 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Phoenix_ZengHao

创作不易,能否打赏一瓶饮料?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值