HihoCoder - 1878 - Palindromes (规律)

题意: 输入n,打印第n个回文数,n最多10万位。
思路:构造似乎不太可能,因为位数太多了,于是考虑n和回文数之间的联系,即打表找规律。
发现,如果首位不是1,那么回文数首位分别为首位减一,中间的数为n剩下数进行回文操作。
如果首位是1,又分为第二位是0和不是0的情况,是0的话,那么把n除去首位进行回文化即可,否则,所求回文数首尾位为9(也就相当于之前首位为10的情况),其余如旧进行回文化。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000000;
string s;
string tmp;
map<string,int > ma;
int main()
{
    ma["1"] = 0;
    ma["2"] = 1;
    ma["3"] = 2;
    ma["4"] = 3;
    ma["5"] = 4;
    ma["6"] = 5;
    ma["7"] = 6;
    ma["8"] = 7;
    ma["9"] = 8;
    ma["10"] = 9;
    ma["11"] = 11;
    ma["12"] = 22;
    ma["13"] = 33;
    ma["14"] = 44;
    ma["15"] = 55;
    ma["16"] = 66;
    ma["17"] = 77;
    ma["18"] = 88;
    ma["19"] = 99;
    int t;
    cin>>t;
    while(t--)
    {
        cin>>s;
        int len =s.size();
        if(len <= 1)
        {
            cout<<ma[s]<<endl;
            continue;
        }
        if(len ==2 &&s[0]=='1')
        {
            cout<<ma[s]<<endl;
            continue;
        }
        if(s[0]!= '1')
        {
            tmp = s.substr(1,len-1);
            cout<<char(s[0]-1);
            cout<<tmp;
            for(int i = tmp.size()-2; i >= 0; i--)
            {
                cout<<tmp[i];
            }
            cout<<char(s[0]-1);
            cout<<endl;
        }
        else
        {
            if(s[1] != '0')
            {
                tmp = s.substr(1);
                cout<<tmp;
                for(int i = tmp.size()-1; i >= 0; i--)
                {
                    cout<<tmp[i];
                }
            }
            else
            {
                tmp = s.substr(2);
                cout<<9;
                cout<<tmp;
                for(int i = tmp.size()-2; i >= 0; i--)
                {
                    cout<<tmp[i];
                }
                cout<<9;
            }
            cout<<endl;
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值