1024 Palindromic Number (25分)

题目大意:给出一个数n和次数k,每次将n中各位数字颠倒后再加到n上,直到n为回文数字结束,输出此时的回文数字n和所用次数。若在k次内无法使得n为回文数字,则输出第k次运算结束后的n和k本身。

思路:由于数字范围较大,需要使用string来计算。对于模拟加法中的两个加数,长度相同,且为另一个数中各位数字倒置后的结果,所以直接进行运算即可实现从低位到高位运算,而不需要将两个数倒置。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

string add(string a,string b){
    string res=""; int pre=0;
    for(int i=0;i<(int)a.length();i++){
        int tem=(a[i]-'0')+(b[i]-'0')+pre;
        pre=tem/10;
        res+=tem%10+'0';
    }
    if(pre) res+=pre+'0';

    reverse(res.begin(),res.end());
    return res;
}

bool judge(string a){
    for(int i=0,j=a.length()-1;i<j;i++,j--)
        if(a[i]!=a[j])
            return false;
    return true;
}

int main(){
    string a,b;
    int k;
    cin>>a>>k;

    for(int i=0;i<k;i++){
        if(judge(a)){
            printf("%s\n%d\n",a.c_str(),i);
            return 0;
        }

        b="";
        for(int j=a.size()-1;j>=0;j--)
            b+=a[j];
        a=add(a,b);
        //printf("%s\n",a.c_str());
    }
    printf("%s\n%d\n",a.c_str(),k);

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值