解题代码
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
struct bign {
int p[1100];
int len;
bign() {
len = 0;
memset(p, 0, sizeof(p));
}
};
bign change(string str) {
bign ret;
ret.len = str.length();
for (int i = 0; i < ret.len; i++)
ret.p[i] = str[ret.len - i - 1] - '0';
return ret;
}
bign add(bign a, bign b) {
bign c;
int carry = 0;
int len1 = a.len;
int len2 = b.len;
int l = max(len1, len2), i;
for (i = 0; i < l; i++) {
int temp = a.p[i] + b.p[i] + carry;
carry = temp / 10;
c.p[c.len++] = temp % 10;
}
while (carry) {
c.p[c.len++] = carry % 10;
carry /= 10;
}
return c;
}
string handle(string str) {
cout << str;
bign a1 = change(str);
reverse(str.begin(), str.end());
while (str[0] == '0') str.erase(str.begin());
cout << " + " << str;
bign a2 = change(str);
bign a3 = add(a1, a2);
reverse(a3.p, a3.p+a3.len);
string a;
for (int i = 0; i < a3.len; i++) a.push_back(a3.p[i] + '0');
while (a[0] == '0') a.erase(a.begin());
cout << " = " << a << endl;
return a;
}
bool isright(string str) {
if (str.length() == 1) return true;
int len = str.length();
for (int i = 0; i <= len / 2; i++)
if (str[i] != str[len - i - 1]) return false;
return true;
}
int main() {
string str;
cin >> str;
int i;
if (isright(str))
cout << str << " is a palindromic number.";
else {
for (i = 0; i < 10; i++) {
str = handle(str);
if (isright(str)) {
cout << str << " is a palindromic number.";
break;
}
}
if (i == 10) cout << "Not found in 10 iterations.";
}
return 0;
}
测试结果
问题整理
1.基础题目。
2.考虑前缀零和一位数的特判情况。