本题是一道大数运算题,通过string和vector来进行大数运算
① 定义string类temp、temp2,vector类 temp1
②先计算出temp和逆temp的运算结果,结果存于temp1
int c=0;
temp1.clear();
//利用string和vector进行大数运算
for(int i=0;i<temp.size();i++){ //①进位c初始化为0
int res=(temp[i]-'0')+(temp[temp.size()-i-1]-'0')+c; //②先将本步计算结果 存入res
if(res>9) temp1.push_back(res-10),c=1; //③如果res>9 ,则保存res-10,并且进位c=1
else temp1.push_back(res), c=0; //④如果res<=9,则保存res, 并且进位c=0
}
if(c==1) temp1.push_back(1); //⑤如果最后一步进位为1,还要再插入一位 “1”
③再把temp1中的倒序结果转为为temp2中的正序结果,类型也由vector转为string
//此时计算的结果已经存到了temp1中,不过是倒序
string temp2;
for(int i=0;i<temp1.size();i++) //通过头插法,将顺序变为正序,同时类型由vector<int> 变回string
temp2.insert(0,1,temp1[i]+'0');
④再让temp=temp2即可
【完整AC代码】
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int k;
string n,temp;
vector<int> temp1;
bool judge(string a){
for(int i=0;i<a.size();i++)
if(a[i]!=a[a.size()-i-1]) return false;
return true;
}
int main()
{
cin>>n>>k;
temp=n;
for(int i=0;i<k;i++){
if(judge(temp)){
cout<<temp<<endl<<i;
return 0;
}
int c=0;
temp1.clear();
//利用string和vector进行大数运算
for(int i=0;i<temp.size();i++){ //①进位c初始化为0
int res=(temp[i]-'0')+(temp[temp.size()-i-1]-'0')+c; //②先将本步计算结果 存入res
if(res>9) temp1.push_back(res-10),c=1; //③如果res>9 ,则保存res-10,并且进位c=1
else temp1.push_back(res), c=0; //④如果res<=9,则保存res, 并且进位c=0
}
if(c==1) temp1.push_back(1); //⑤如果最后一步进位为1,还要再插入一位 “1”
//此时计算的结果已经存到了temp1中,不过是倒序
string temp2;
for(int i=0;i<temp1.size();i++) //通过头插法,将顺序变为正序,同时类型由vector<int> 变回string
temp2.insert(0,1,temp1[i]+'0');
temp=temp2; //再将temp2赋值给temp1
}
cout<<temp<<endl<<k;
return 0;
}