题目大意:给出一个数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;
}