https://pintia.cn/problem-sets/994805260223102976/problems/994805261754023936
做了宇宙最强加法器那道题,对这道题的做法很有帮助。因为整数实在是太大,必须借用string来做加法。 也学习了reverse的用法。
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool isHuiWen(string str){
for(int i=0, j=str.size()-1; i<j; i++, j--){
if(str[i] != str[j]){
return false;
}
}
return true;
}
string jia(string a, string b){
string res;
int jin=0, sum;
for(int i=a.size()-1, j=b.size()-1; i>=0 || j>=0 || jin>0; i--, j--){
sum = 0;
if(i>=0)
sum += a[i]-'0';
if(j>=0)
sum += b[j]-'0';
sum += jin;
jin = sum/10;
res = to_string(sum%10)+res;
}
return res;
}
int main() {
int count = 0;
string a, b, c;
cin >> a;
while(!isHuiWen(a)){
b = a;
reverse(b.begin(), b.end());
c = jia(a, b);
cout << a << " + " << b << " = " << c << endl;
count ++;
if(count >= 10){
cout << "Not found in 10 iterations." << endl;
break;
}
a = c;
}
if(count < 10){
cout << a << " is a palindromic number." << endl;
}
return 0;
}