1024 Palindromic Number (25分)
分析
大整数加法,需要处理字符串相加,设置一个tag来标记进位
代码
#include<iostream>
#include<string>
#include<string.h>
#include<algorithm>
using namespace std;
string getsum(string x, string y) {
bool tag = false;
for (int i = x.size() - 1; i >= 0; --i) {
int d = x[i] + y[i] - 2 * '0' + tag;
tag = false;
if (d >= 10) {
tag = true;
d -= 10;
}
x[i] = d + '0';
}
if (tag)x.insert(x.begin(), '1');
return x;
}
int main() {
string a, ra;
int n, i = 0;
cin >> a >> n;
while (i < n) {
ra = a;
reverse(ra.begin(), ra.end());
if (strcmp(a.c_str(), ra.c_str()) == 0)break;
a = getsum(a, ra);
++i;
}
cout << a << endl << i;
return 0;
}