本题链接:1136 A Delayed Palindrome - PAT (Advanced Level) Practice (pintia.cn)
题意:
给定一个数字a,如该数不是回文数,则将a翻转得到b,判断a+b是否为回文数,如果不是则再次执行翻转并相加,直到结果为回文数,如果十次后得不到回文数则结束。
本题为经典的大整数运算(因为题中给出数字<=1000digits)
代码:
#include<iostream>
#include<cmath>
#include<string>
#include<algorithm>
using namespace std;
string add(string a,string b) {
string ans;
int carry = 0;
for (int i = 0; i < a.size(); i++) {
int num = (a[i] - '0') + (b[i] - '0') + carry;
carry = 0;
if (num >= 10) {
num -= 10;
carry = 1;
}
ans += char(num + '0');
}
if (carry == 1) ans += '1';
reverse(ans.begin(), ans.end());
return ans;
}
int main() {
string num;
cin >> num;
int i = 0;
for (i = 0; i < 10; i++) {
string rNum = num;
reverse(rNum.begin(), rNum.end());
if (num == rNum) {
cout << num << " is a palindromic number.\n";
break;
}else {
cout << num << " + " << rNum << " = " << add(num, rNum) << endl;
num = add(num,rNum);
}
}
if (i == 10) {
printf("Not found in 10 iterations.");
}
return 0;
}