原文链接:我的个人博客原题链接
考点
字符串处理;大整数加法
思路
题目要求一个数和它的逆序数进行相加得到一个新的数,判断得到的数是否为回文数。重复这个操作,直到得到回文数。要求在十次操作之内完成。题目给定的数是<=1000位,因此这里不能用普通的加法,必须要使用字符串来表示数字,并实现大数加法。代码如下
代码
#include <bits/stdc++.h>
using namespace std;
string add(string s1){
string s2 = s1;
reverse(s2.begin(),s2.end());//反转链表
// cout<<s1<<"\t"<<s2<<endl;
string ans(s1.length()+1,'0');
int t=0,i;//进位
for(i=0;s1[i];i++){
t += (s1[i]-'0')+(s2[i]-'0');
ans[i] = t%10+'0';
t /= 10;//进位
}
ans[i] = t+'0';
reverse(ans.begin(),ans.end());
ans = ans.substr(ans.find_first_not_of('0'));
cout<<s1<<" + "<<s2<<" = "<<ans<<endl;
return ans;
}
//判断是否是回文数
bool isH(string s){
int i=0,j=s.length()-1;
for(;s[i]==s[j];i++,j--);
if(i>j) return true;
else return false;
}
//N最大1
int main(){
string s1;
cin>>s1;
int cnt=0;
while(++cnt<=10){
if(isH(s1)){
cout<<s1<<" is a palindromic number."<<endl;
return 0;
}
s1 = add(s1);
}
cout<<"Not found in 10 iterations."<<endl;
return 0;
}