题意:
给出一个数N(N<=10^10),最多可操作K次(K<=100),每次操作为这个数和其反转之后的数相加,若得到的结果为回文数,则输出;若在K次迭代后仍然不是回文数,在输出第K次操作后的结果。
思路:
因为int型最大可表示为2^31-1=2,147,483,647,显然本题的范围已经超出了int可表示的范围了。因此可用大整数的思想。
大整数相加时最后要注意一下进位carry是否大于0。
这里用到一点小trick,需要熟悉string的
构造函数。这里使用了
string(size_type count, char ch) 。而比如
9+'0' 这样的写法表示的是int型整数"9"对应的char型。
代码:
#include <iostream> #include <string> #include <algorithm> using namespace std; bool judge(const string& str) { int i=0,j=str.size()-1; while(i<j){ if(str[i]!=str[j]) return false; i++; j--; } return true; } string add(const string& a,const string& b) { string c; int carry=0; for(int i=a.size()-1;i>=0;i--){ int temp=carry+a[i]-'0'+b[i]-'0'; c=string(1,temp%10+'0')+c; carry=temp/10; } if(carry>0) c=string(1,carry+'0')+c; return c; } int main() { int k,cnt=0; string str,tmp; cin>>str>>k; while(cnt<=k){ if(judge(str)){ cout<<str<<'\n'<<cnt<<'\n'; break; } if(cnt==k) tmp=str; string r_str=str; reverse(r_str.begin(),r_str.end()); str=add(str,r_str); cnt++; } if(cnt==k+1) cout<<tmp<<'\n'<<k<<'\n'; return 0; }