题意:输入一个数,把它和自己的转置相加,在10次这种操作之内看是否可以得到一个回文数。
思路:直接模拟。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAX_N = 1010;
char a[2][MAX_N], tmp[MAX_N];
int ind;
bool isPa(char s[]) {
int len = strlen(s);
for (int i = 0; i * 2 < len; i++) {
if (s[i] != s[len-i-1]) return false;
}
return true;
}
void rev(char a[], char ans[]) {
int len = strlen(a);
for (int i = 0; i < len; i++) {
ans[len-i-1] = a[i];
}
ans[len] = '\0';
}
void cal(char a[], char b[], char ans[]) {
int len = strlen(a);
int flag = 0;
for (int i = 0; i < len; i++) {
int t = (a[i]-'0') + (b[i]-'0') + flag;
flag = 0;
if (t > 9) {
flag = t / 10; t %= 10;
}
ans[i] = t + '0';
}
if (flag) ans[len++] = flag + '0';
ans[len] = '\0';
for (int i = 0; i * 2 < len; i++) {
swap(ans[i], ans[len-i-1]);
}
}
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf("%s", a[0]);
bool flag = false; ind = 0;
if (isPa(a[0])) {
printf("%s is a palindromic number.\n", a[0]);
return 0;
}
for (int i = 0; i < 10; i++) {
rev(a[ind], a[ind^1]);
cal(a[ind], a[ind^1], tmp);
printf("%s + %s = %s\n", a[ind], a[ind^1], tmp);
if (isPa(tmp)) {
flag = true;
printf("%s is a palindromic number.\n", tmp);
break;
}
strcpy(a[ind], tmp);
}
if (!flag) {
printf("Not found in 10 iterations.\n");
}
return 0;
}