代码
#include <iostream>
#include <sstream>
using namespace std;
string intToStr(int t) {
stringstream ss;
ss<<t;
string s;
ss>>s;
return s;
}
int main() {
string s;
cin>>s;
string s2;
for(int i=s.length()-1; i>=0; i--) {
s2 += s.at(i);
}
int count = 0;
int jinwei = 0;
while(s.compare(s2) && count<10) {
string ans;
for(int i=s.length()-1; i>=0; i--) {
int tmp = s.at(i)-'0' + s2.at(i)-'0' + jinwei;
jinwei = tmp/10;
tmp = tmp%10;
ans = intToStr(tmp) + ans;
}
if(jinwei) {
ans = intToStr(jinwei) + ans;
jinwei = 0;
}
count++;
cout<<s<<" + "<<s2<<" = "<<ans<<endl;
s2 = "";
for(int i=ans.length()-1; i>=0; i--) {
s2 += ans.at(i);
}
s = ans;
}
if(count==10){
cout<<"Not found in 10 iterations."<<endl;
}
else{
cout<<s<<" is a palindromic number."<<endl;
}
return 0;
}
注解
1、因为涉及到大数字,所以不能用int和long,只能用字符串或字符数组处理,本题选择用字符串。
2、处理大整数的加法,主要是考虑到两个加数和其进位。千万不要漏掉进位,和正确处理进位是关键。大数减法、大数乘法的关键也都是处理好进位。大数乘法相对更复杂些,建议用字符数组的形式。但要考虑到前导0的问题。
3、用count来计数,控制何时结束循环。